This repository has been archived by the owner on Nov 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 94
/
fbpca.py
2132 lines (1740 loc) · 68.4 KB
/
fbpca.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
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Functions for principal component analysis (PCA) and accuracy checks
---------------------------------------------------------------------
This module contains eight functions:
pca
principal component analysis (singular value decomposition)
eigens
eigendecomposition of a self-adjoint matrix
eigenn
eigendecomposition of a nonnegative-definite self-adjoint matrix
diffsnorm
spectral-norm accuracy of a singular value decomposition
diffsnormc
spectral-norm accuracy of a centered singular value decomposition
diffsnorms
spectral-norm accuracy of a Schur decomposition
mult
default matrix multiplication
set_matrix_mult
re-definition of the matrix multiplication function "mult"
---------------------------------------------------------------------
Copyright 2018 Facebook Inc.
All rights reserved.
"Software" means the fbpca software distributed by Facebook Inc.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions, and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions, and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
* Neither the name Facebook nor the names of its contributors may be
used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Additional grant of patent rights:
Facebook hereby grants you a perpetual, worldwide, royalty-free,
non-exclusive, irrevocable (subject to the termination provision
below) license under any rights in any patent claims owned by
Facebook, to make, have made, use, sell, offer to sell, import, and
otherwise transfer the Software. For avoidance of doubt, no license
is granted under Facebook's rights in any patent claims that are
infringed by (i) modifications to the Software made by you or a third
party, or (ii) the Software in combination with any software or other
technology provided by you or a third party.
The license granted hereunder will terminate, automatically and
without notice, for anyone that makes any claim (including by filing
any lawsuit, assertion, or other action) alleging (a) direct,
indirect, or contributory infringement or inducement to infringe any
patent: (i) by Facebook or any of its subsidiaries or affiliates,
whether or not such claim is related to the Software, (ii) by any
party if such claim arises in whole or in part from any software,
product or service of Facebook or any of its subsidiaries or
affiliates, whether or not such claim is related to the Software, or
(iii) by any party relating to the Software; or (b) that any right in
any patent claim of Facebook is invalid or unenforceable.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import unittest
import math
import numpy as np
from scipy.linalg import cholesky, eigh, lu, qr, svd, norm, solve
from scipy.sparse import coo_matrix, issparse, spdiags
def diffsnorm(A, U, s, Va, n_iter=20):
"""
2-norm accuracy of an approx to a matrix.
Computes an estimate snorm of the spectral norm (the operator norm
induced by the Euclidean vector norm) of A - U diag(s) Va, using
n_iter iterations of the power method started with a random vector;
n_iter must be a positive integer.
Increasing n_iter improves the accuracy of the estimate snorm of
the spectral norm of A - U diag(s) Va.
Notes
-----
To obtain repeatable results, reset the seed for the pseudorandom
number generator.
Parameters
----------
A : array_like
first matrix in A - U diag(s) Va whose spectral norm is being
estimated
U : array_like
second matrix in A - U diag(s) Va whose spectral norm is being
estimated
s : array_like
vector in A - U diag(s) Va whose spectral norm is being
estimated
Va : array_like
fourth matrix in A - U diag(s) Va whose spectral norm is being
estimated
n_iter : int, optional
number of iterations of the power method to conduct;
n_iter must be a positive integer, and defaults to 20
Returns
-------
float
an estimate of the spectral norm of A - U diag(s) Va (the
estimate fails to be accurate with exponentially low prob. as
n_iter increases; see references DM1_, DM2_, and DM3_ below)
Examples
--------
>>> from fbpca import diffsnorm, pca
>>> from numpy.random import uniform
>>> from scipy.linalg import svd
>>>
>>> A = uniform(low=-1.0, high=1.0, size=(100, 2))
>>> A = A.dot(uniform(low=-1.0, high=1.0, size=(2, 100)))
>>> (U, s, Va) = svd(A, full_matrices=False)
>>> A = A / s[0]
>>>
>>> (U, s, Va) = pca(A, 2, True)
>>> err = diffsnorm(A, U, s, Va)
>>> print(err)
This example produces a rank-2 approximation U diag(s) Va to A such
that the columns of U are orthonormal, as are the rows of Va, and
the entries of s are all nonnegative and are nonincreasing.
diffsnorm(A, U, s, Va) outputs an estimate of the spectral norm of
A - U diag(s) Va, which should be close to the machine precision.
References
----------
.. [DM1] Jacek Kuczynski and Henryk Wozniakowski, Estimating the
largest eigenvalues by the power and Lanczos methods with
a random start, SIAM Journal on Matrix Analysis and
Applications, 13 (4): 1094-1122, 1992.
.. [DM2] Edo Liberty, Franco Woolfe, Per-Gunnar Martinsson,
Vladimir Rokhlin, and Mark Tygert, Randomized algorithms
for the low-rank approximation of matrices, Proceedings of
the National Academy of Sciences (USA), 104 (51):
20167-20172, 2007. (See the appendix.)
.. [DM3] Franco Woolfe, Edo Liberty, Vladimir Rokhlin, and Mark
Tygert, A fast randomized algorithm for the approximation
of matrices, Applied and Computational Harmonic Analysis,
25 (3): 335-366, 2008. (See Section 3.4.)
See also
--------
diffsnormc, pca
"""
(m, n) = A.shape
(m2, k) = U.shape
k2 = len(s)
l = len(s)
(l2, n2) = Va.shape
assert m == m2
assert k == k2
assert l == l2
assert n == n2
assert n_iter >= 1
if np.isrealobj(A) and np.isrealobj(U) and np.isrealobj(s) and \
np.isrealobj(Va):
isreal = True
else:
isreal = False
# Promote the types of integer data to float data.
dtype = (A * 1.0).dtype
if m >= n:
#
# Generate a random vector x.
#
if isreal:
x = np.random.normal(size=(n, 1)).astype(dtype)
else:
x = np.random.normal(size=(n, 1)).astype(dtype) \
+ 1j * np.random.normal(size=(n, 1)).astype(dtype)
x = x / norm(x)
#
# Run n_iter iterations of the power method.
#
for it in range(n_iter):
#
# Set y = (A - U diag(s) Va)x.
#
y = mult(A, x) - U.dot(np.diag(s).dot(Va.dot(x)))
#
# Set x = (A' - Va' diag(s)' U')y.
#
x = mult(y.conj().T, A).conj().T \
- Va.conj().T.dot(np.diag(s).conj().T.dot(U.conj().T.dot(y)))
#
# Normalize x, memorizing its Euclidean norm.
#
snorm = norm(x)
if snorm == 0:
return 0
x = x / snorm
snorm = math.sqrt(snorm)
if m < n:
#
# Generate a random vector y.
#
if isreal:
y = np.random.normal(size=(m, 1)).astype(dtype)
else:
y = np.random.normal(size=(m, 1)).astype(dtype) \
+ 1j * np.random.normal(size=(m, 1)).astype(dtype)
y = y / norm(y)
#
# Run n_iter iterations of the power method.
#
for it in range(n_iter):
#
# Set x = (A' - Va' diag(s)' U')y.
#
x = mult(y.conj().T, A).conj().T \
- Va.conj().T.dot(np.diag(s).conj().T.dot(U.conj().T.dot(y)))
#
# Set y = (A - U diag(s) Va)x.
#
y = mult(A, x) - U.dot(np.diag(s).dot(Va.dot(x)))
#
# Normalize y, memorizing its Euclidean norm.
#
snorm = norm(y)
if snorm == 0:
return 0
y = y / snorm
snorm = math.sqrt(snorm)
return snorm
class TestDiffsnorm(unittest.TestCase):
def test_dense(self):
logging.info('running TestDiffsnorm.test_dense...')
logging.info('err =')
for dtype in ['float16', 'float32', 'float64']:
if dtype == 'float64':
prec = .1e-10
elif dtype == 'float32':
prec = .1e-2
else:
prec = .1e0
for (m, n) in [(200, 100), (100, 200), (100, 100)]:
for isreal in [True, False]:
if isreal:
A = np.random.normal(size=(m, n)).astype(dtype)
if not isreal:
A = np.random.normal(size=(m, n)).astype(dtype) \
+ 1j * np.random.normal(size=(m, n)).astype(dtype)
(U, s, Va) = svd(A, full_matrices=False)
snorm = diffsnorm(A, U, s, Va)
logging.info(snorm)
self.assertTrue(snorm < prec * s[0])
def test_sparse(self):
logging.info('running TestDiffsnorm.test_sparse...')
logging.info('err =')
for dtype in ['float16', 'float32', 'float64']:
if dtype == 'float64':
prec = .1e-10
elif dtype == 'float32':
prec = .1e-2
else:
prec = .1e0
for (m, n) in [(200, 100), (100, 200), (100, 100)]:
for isreal in [True, False]:
if isreal:
A = 2 * spdiags(
np.arange(min(m, n)) + 1, 0, m, n).astype(dtype)
if not isreal:
A = 2 * spdiags(
np.arange(min(m, n)) + 1, 0, m, n).astype(dtype) \
* (1 + 1j)
A = A - spdiags(np.arange(min(m, n) + 1), 1, m, n)
A = A - spdiags(np.arange(min(m, n)) + 1, -1, m, n)
(U, s, Va) = svd(A.todense(), full_matrices=False)
A = A / s[0]
(U, s, Va) = svd(A.todense(), full_matrices=False)
snorm = diffsnorm(A, U, s, Va)
logging.info(snorm)
self.assertTrue(snorm < prec * s[0])
def diffsnormc(A, U, s, Va, n_iter=20):
"""
2-norm approx error to a matrix upon centering.
Computes an estimate snorm of the spectral norm (the operator norm
induced by the Euclidean vector norm) of C(A) - U diag(s) Va, using
n_iter iterations of the power method started with a random vector,
where C(A) refers to A from the input, after centering its columns;
n_iter must be a positive integer.
Increasing n_iter improves the accuracy of the estimate snorm of
the spectral norm of C(A) - U diag(s) Va, where C(A) refers to A
after centering its columns.
Notes
-----
To obtain repeatable results, reset the seed for the pseudorandom
number generator.
Parameters
----------
A : array_like
first matrix in the column-centered A - U diag(s) Va whose
spectral norm is being estimated
U : array_like
second matrix in the column-centered A - U diag(s) Va whose
spectral norm is being estimated
s : array_like
vector in the column-centered A - U diag(s) Va whose spectral
norm is being estimated
Va : array_like
fourth matrix in the column-centered A - U diag(s) Va whose
spectral norm is being estimated
n_iter : int, optional
number of iterations of the power method to conduct;
n_iter must be a positive integer, and defaults to 20
Returns
-------
float
an estimate of the spectral norm of the column-centered A
- U diag(s) Va (the estimate fails to be accurate with
exponentially low probability as n_iter increases; see
references DC1_, DC2_, and DC3_ below)
Examples
--------
>>> from fbpca import diffsnormc, pca
>>> from numpy.random import uniform
>>> from scipy.linalg import svd
>>>
>>> A = uniform(low=-1.0, high=1.0, size=(100, 2))
>>> A = A.dot(uniform(low=-1.0, high=1.0, size=(2, 100)))
>>> (U, s, Va) = svd(A, full_matrices=False)
>>> A = A / s[0]
>>>
>>> (U, s, Va) = pca(A, 2, False)
>>> err = diffsnormc(A, U, s, Va)
>>> print(err)
This example produces a rank-2 approximation U diag(s) Va to the
column-centered A such that the columns of U are orthonormal, as
are the rows of Va, and the entries of s are nonnegative and
nonincreasing. diffsnormc(A, U, s, Va) outputs an estimate of the
spectral norm of the column-centered A - U diag(s) Va, which
should be close to the machine precision.
References
----------
.. [DC1] Jacek Kuczynski and Henryk Wozniakowski, Estimating the
largest eigenvalues by the power and Lanczos methods with
a random start, SIAM Journal on Matrix Analysis and
Applications, 13 (4): 1094-1122, 1992.
.. [DC2] Edo Liberty, Franco Woolfe, Per-Gunnar Martinsson,
Vladimir Rokhlin, and Mark Tygert, Randomized algorithms
for the low-rank approximation of matrices, Proceedings of
the National Academy of Sciences (USA), 104 (51):
20167-20172, 2007. (See the appendix.)
.. [DC3] Franco Woolfe, Edo Liberty, Vladimir Rokhlin, and Mark
Tygert, A fast randomized algorithm for the approximation
of matrices, Applied and Computational Harmonic Analysis,
25 (3): 335-366, 2008. (See Section 3.4.)
See also
--------
diffsnorm, pca
"""
(m, n) = A.shape
(m2, k) = U.shape
k2 = len(s)
l = len(s)
(l2, n2) = Va.shape
assert m == m2
assert k == k2
assert l == l2
assert n == n2
assert n_iter >= 1
if np.isrealobj(A) and np.isrealobj(U) and np.isrealobj(s) and \
np.isrealobj(Va):
isreal = True
else:
isreal = False
# Promote the types of integer data to float data.
dtype = (A * 1.0).dtype
#
# Calculate the average of the entries in every column.
#
c = A.sum(axis=0) / m
c = c.reshape((1, n))
if m >= n:
#
# Generate a random vector x.
#
if isreal:
x = np.random.normal(size=(n, 1)).astype(dtype)
else:
x = np.random.normal(size=(n, 1)).astype(dtype) \
+ 1j * np.random.normal(size=(n, 1)).astype(dtype)
x = x / norm(x)
#
# Run n_iter iterations of the power method.
#
for it in range(n_iter):
#
# Set y = (A - ones(m,1)*c - U diag(s) Va)x.
#
y = mult(A, x) - np.ones((m, 1), dtype=dtype).dot(c.dot(x)) \
- U.dot(np.diag(s).dot(Va.dot(x)))
#
# Set x = (A' - c'*ones(1,m) - Va' diag(s)' U')y.
#
x = mult(y.conj().T, A).conj().T \
- c.conj().T.dot(np.ones((1, m), dtype=dtype).dot(y)) \
- Va.conj().T.dot(np.diag(s).conj().T.dot(U.conj().T.dot(y)))
#
# Normalize x, memorizing its Euclidean norm.
#
snorm = norm(x)
if snorm == 0:
return 0
x = x / snorm
snorm = math.sqrt(snorm)
if m < n:
#
# Generate a random vector y.
#
if isreal:
y = np.random.normal(size=(m, 1)).astype(dtype)
else:
y = np.random.normal(size=(m, 1)).astype(dtype) \
+ 1j * np.random.normal(size=(m, 1)).astype(dtype)
y = y / norm(y)
#
# Run n_iter iterations of the power method.
#
for it in range(n_iter):
#
# Set x = (A' - c'*ones(1,m) - Va' diag(s)' U')y.
#
x = mult(y.conj().T, A).conj().T \
- c.conj().T.dot(np.ones((1, m), dtype=dtype).dot(y)) \
- Va.conj().T.dot(np.diag(s).conj().T.dot(U.conj().T.dot(y)))
#
# Set y = (A - ones(m,1)*c - U diag(s) Va)x.
#
y = mult(A, x) - np.ones((m, 1), dtype=dtype).dot(c.dot(x)) \
- U.dot(np.diag(s).dot(Va.dot(x)))
#
# Normalize y, memorizing its Euclidean norm.
#
snorm = norm(y)
if snorm == 0:
return 0
y = y / snorm
snorm = math.sqrt(snorm)
return snorm
class TestDiffsnormc(unittest.TestCase):
def test_dense(self):
logging.info('running TestDiffsnormc.test_dense...')
logging.info('err =')
for dtype in ['float16', 'float32', 'float64']:
if dtype == 'float64':
prec = .1e-10
elif dtype == 'float32':
prec = .1e-2
else:
prec = .1e0
for (m, n) in [(200, 100), (100, 200), (100, 100)]:
for isreal in [True, False]:
if isreal:
A = np.random.normal(size=(m, n)).astype(dtype)
if not isreal:
A = np.random.normal(size=(m, n)).astype(dtype) \
+ 1j * np.random.normal(size=(m, n)).astype(dtype)
c = A.sum(axis=0) / m
c = c.reshape((1, n))
Ac = A - np.ones((m, 1), dtype=dtype).dot(c)
(U, s, Va) = svd(Ac, full_matrices=False)
snorm = diffsnormc(A, U, s, Va)
logging.info(snorm)
self.assertTrue(snorm < prec * s[0])
def test_sparse(self):
logging.info('running TestDiffsnormc.test_sparse...')
logging.info('err =')
for dtype in ['float16', 'float32', 'float64']:
if dtype == 'float64':
prec = .1e-10
elif dtype == 'float32':
prec = .1e-2
else:
prec = .1e0
for (m, n) in [(200, 100), (100, 200), (100, 100)]:
for isreal in [True, False]:
if isreal:
A = 2 * spdiags(
np.arange(min(m, n)) + 1, 0, m, n).astype(dtype)
if not isreal:
A = 2 * spdiags(
np.arange(min(m, n)) + 1, 0, m, n).astype(dtype) \
* (1 + 1j)
A = A - spdiags(np.arange(min(m, n) + 1), 1, m, n)
A = A - spdiags(np.arange(min(m, n)) + 1, -1, m, n)
(U, s, Va) = svd(A.todense(), full_matrices=False)
A = A / s[0]
Ac = A.todense()
c = Ac.sum(axis=0) / m
c = c.reshape((1, n))
Ac = Ac - np.ones((m, 1), dtype=dtype).dot(c)
(U, s, Va) = svd(Ac, full_matrices=False)
snorm = diffsnormc(A, U, s, Va)
logging.info(snorm)
self.assertTrue(snorm < prec * s[0])
def diffsnorms(A, S, V, n_iter=20):
"""
2-norm accuracy of a Schur decomp. of a matrix.
Computes an estimate snorm of the spectral norm (the operator norm
induced by the Euclidean vector norm) of A-VSV', using n_iter
iterations of the power method started with a random vector;
n_iter must be a positive integer.
Increasing n_iter improves the accuracy of the estimate snorm of
the spectral norm of A-VSV'.
Notes
-----
To obtain repeatable results, reset the seed for the pseudorandom
number generator.
Parameters
----------
A : array_like
first matrix in A-VSV' whose spectral norm is being estimated
S : array_like
third matrix in A-VSV' whose spectral norm is being estimated
V : array_like
second matrix in A-VSV' whose spectral norm is being estimated
n_iter : int, optional
number of iterations of the power method to conduct;
n_iter must be a positive integer, and defaults to 20
Returns
-------
float
an estimate of the spectral norm of A-VSV' (the estimate fails
to be accurate with exponentially low probability as n_iter
increases; see references DS1_, DS2_, and DS3_ below)
Examples
--------
>>> from fbpca import diffsnorms, eigenn
>>> from numpy import diag
>>> from numpy.random import uniform
>>> from scipy.linalg import svd
>>>
>>> A = uniform(low=-1.0, high=1.0, size=(2, 100))
>>> A = A.T.dot(A)
>>> (U, s, Va) = svd(A, full_matrices=False)
>>> A = A / s[0]
>>>
>>> (d, V) = eigenn(A, 2)
>>> err = diffsnorms(A, diag(d), V)
>>> print(err)
This example produces a rank-2 approximation V diag(d) V' to A
such that the columns of V are orthonormal and the entries of d
are nonnegative and are nonincreasing.
diffsnorms(A, diag(d), V) outputs an estimate of the spectral norm
of A - V diag(d) V', which should be close to the machine
precision.
References
----------
.. [DS1] Jacek Kuczynski and Henryk Wozniakowski, Estimating the
largest eigenvalues by the power and Lanczos methods with
a random start, SIAM Journal on Matrix Analysis and
Applications, 13 (4): 1094-1122, 1992.
.. [DS2] Edo Liberty, Franco Woolfe, Per-Gunnar Martinsson,
Vladimir Rokhlin, and Mark Tygert, Randomized algorithms
for the low-rank approximation of matrices, Proceedings of
the National Academy of Sciences (USA), 104 (51):
20167-20172, 2007. (See the appendix.)
.. [DS3] Franco Woolfe, Edo Liberty, Vladimir Rokhlin, and Mark
Tygert, A fast randomized algorithm for the approximation
of matrices, Applied and Computational Harmonic Analysis,
25 (3): 335-366, 2008. (See Section 3.4.)
See also
--------
eigenn, eigens
"""
(m, n) = A.shape
(m2, k) = V.shape
(k2, k3) = S.shape
assert m == n
assert m == m2
assert k == k2
assert k2 == k3
assert n_iter >= 1
if np.isrealobj(A) and np.isrealobj(V) and np.isrealobj(S):
isreal = True
else:
isreal = False
# Promote the types of integer data to float data.
dtype = (A * 1.0).dtype
#
# Generate a random vector x.
#
if isreal:
x = np.random.normal(size=(n, 1)).astype(dtype)
else:
x = np.random.normal(size=(n, 1)).astype(dtype) \
+ 1j * np.random.normal(size=(n, 1)).astype(dtype)
x = x / norm(x)
#
# Run n_iter iterations of the power method.
#
for it in range(n_iter):
#
# Set y = (A-VSV')x.
#
y = mult(A, x) - V.dot(S.dot(V.conj().T.dot(x)))
#
# Set x = (A'-VS'V')y.
#
x = mult(y.conj().T, A).conj().T \
- V.dot(S.conj().T.dot(V.conj().T.dot(y)))
#
# Normalize x, memorizing its Euclidean norm.
#
snorm = norm(x)
if snorm == 0:
return 0
x = x / snorm
snorm = math.sqrt(snorm)
return snorm
class TestDiffsnorms(unittest.TestCase):
def test_dense(self):
logging.info('running TestDiffsnorms.test_dense...')
logging.info('err =')
for dtype in ['float16', 'float32', 'float64']:
if dtype == 'float64':
prec = .1e-10
elif dtype == 'float32':
prec = .1e-2
else:
prec = .1e0
for n in [100, 200]:
for isreal in [True, False]:
if isreal:
A = np.random.normal(size=(n, n)).astype(dtype)
if not isreal:
A = np.random.normal(size=(n, n)).astype(dtype) \
+ 1j * np.random.normal(size=(n, n)).astype(dtype)
(U, s, Va) = svd(A, full_matrices=True)
T = (np.diag(s).dot(Va)).dot(U)
snorm = diffsnorms(A, T, U)
logging.info(snorm)
self.assertTrue(snorm < prec * s[0])
def test_sparse(self):
logging.info('running TestDiffsnorms.test_sparse...')
logging.info('err =')
for dtype in ['float16', 'float32', 'float64']:
if dtype == 'float64':
prec = .1e-10
elif dtype == 'float32':
prec = .1e-2
else:
prec = .1e0
for n in [100, 200]:
for isreal in [True, False]:
if isreal:
A = 2 * spdiags(
np.arange(n) + 1, 0, n, n).astype(dtype)
if not isreal:
A = 2 * spdiags(
np.arange(n) + 1, 0, n, n).astype(dtype) * (1 + 1j)
A = A - spdiags(np.arange(n + 1), 1, n, n)
A = A - spdiags(np.arange(n) + 1, -1, n, n)
(U, s, Va) = svd(A.todense(), full_matrices=False)
A = A / s[0]
A = A.tocoo()
(U, s, Va) = svd(A.todense(), full_matrices=True)
T = (np.diag(s).dot(Va)).dot(U)
snorm = diffsnorms(A, T, U)
logging.info(snorm)
self.assertTrue(snorm < prec * s[0])
def eigenn(A, k=6, n_iter=4, l=None):
"""
Eigendecomposition of a NONNEGATIVE-DEFINITE matrix.
Constructs a nearly optimal rank-k approximation V diag(d) V' to a
NONNEGATIVE-DEFINITE matrix A, using n_iter normalized power
iterations, with block size l, started with an n x l random matrix,
when A is n x n; the reference EGN_ below explains "nearly
optimal." k must be a positive integer <= the dimension n of A,
n_iter must be a nonnegative integer, and l must be a positive
integer >= k.
The rank-k approximation V diag(d) V' comes in the form of an
eigendecomposition -- the columns of V are orthonormal and d is a
real vector such that its entries are nonnegative and nonincreasing.
V is n x k and len(d) = k, when A is n x n.
Increasing n_iter or l improves the accuracy of the approximation
V diag(d) V'; the reference EGN_ below describes how the accuracy
depends on n_iter and l. Please note that even n_iter=1 guarantees
superb accuracy, whether or not there is any gap in the singular
values of the matrix A being approximated, at least when measuring
accuracy as the spectral norm || A - V diag(d) V' || of the matrix
A - V diag(d) V' (relative to the spectral norm ||A|| of A).
Notes
-----
THE MATRIX A MUST BE SELF-ADJOINT AND NONNEGATIVE DEFINITE.
To obtain repeatable results, reset the seed for the pseudorandom
number generator.
The user may ascertain the accuracy of the approximation
V diag(d) V' to A by invoking diffsnorms(A, numpy.diag(d), V).
Parameters
----------
A : array_like, shape (n, n)
matrix being approximated
k : int, optional
rank of the approximation being constructed;
k must be a positive integer <= the dimension of A, and
defaults to 6
n_iter : int, optional
number of normalized power iterations to conduct;
n_iter must be a nonnegative integer, and defaults to 4
l : int, optional
block size of the normalized power iterations;
l must be a positive integer >= k, and defaults to k+2
Returns
-------
d : ndarray, shape (k,)
vector of length k in the rank-k approximation V diag(d) V'
to A, such that its entries are nonnegative and nonincreasing
V : ndarray, shape (n, k)
n x k matrix in the rank-k approximation V diag(d) V' to A,
where A is n x n
Examples
--------
>>> from fbpca import diffsnorms, eigenn
>>> from numpy import diag
>>> from numpy.random import uniform
>>> from scipy.linalg import svd
>>>
>>> A = uniform(low=-1.0, high=1.0, size=(2, 100))
>>> A = A.T.dot(A)
>>> (U, s, Va) = svd(A, full_matrices=False)
>>> A = A / s[0]
>>>
>>> (d, V) = eigenn(A, 2)
>>> err = diffsnorms(A, diag(d), V)
>>> print(err)
This example produces a rank-2 approximation V diag(d) V' to A
such that the columns of V are orthonormal and the entries of d
are nonnegative and nonincreasing.
diffsnorms(A, diag(d), V) outputs an estimate of the spectral norm
of A - V diag(d) V', which should be close to the machine
precision.
References
----------
.. [EGN] Nathan Halko, Per-Gunnar Martinsson, and Joel Tropp,
Finding structure with randomness: probabilistic
algorithms for constructing approximate matrix
decompositions, arXiv:0909.4061 [math.NA; math.PR], 2009
(available at `arXiv <http://arxiv.org/abs/0909.4061>`_).
See also
--------
diffsnorms, eigens, pca
"""
if l is None:
l = k + 2
(m, n) = A.shape
assert m == n
assert k > 0
assert k <= n
assert n_iter >= 0
assert l >= k
if np.isrealobj(A):
isreal = True
else:
isreal = False
# Promote the types of integer data to float data.
dtype = (A * 1.0).dtype
#
# Check whether A is self-adjoint to nearly the machine precision.
#
x = np.random.uniform(low=-1.0, high=1.0, size=(n, 1)).astype(dtype)
y = mult(A, x)
z = mult(x.conj().T, A).conj().T
if dtype == 'float16':
prec = .1e-1
elif dtype in ['float32', 'complex64']:
prec = .1e-3
else:
prec = .1e-11
assert (norm(y - z) <= prec * norm(y)) and \
(norm(y - z) <= prec * norm(z))
#
# Eigendecompose A directly if l >= n/1.25.
#
if l >= n / 1.25:
(d, V) = eigh(A.todense() if issparse(A) else A)
#
# Retain only the entries of d with the k greatest absolute
# values and the corresponding columns of V.
#
idx = abs(d).argsort()[-k:][::-1]
return abs(d[idx]), V[:, idx]
#
# Apply A to a random matrix, obtaining Q.
#
if isreal:
R = np.random.uniform(low=-1.0, high=1.0, size=(n, l)).astype(dtype)
if not isreal:
R = np.random.uniform(low=-1.0, high=1.0, size=(n, l)).astype(dtype)
R += 1j * np.random.uniform(low=-1.0, high=1.0, size=(n, l)) \
.astype(dtype)
Q = mult(A, R)
#
# Form a matrix Q whose columns constitute a well-conditioned basis
# for the columns of the earlier Q.
#
if n_iter == 0:
anorm = 0
for j in range(l):
anorm = max(anorm, norm(Q[:, j]) / norm(R[:, j]))
(Q, _) = qr(Q, mode='economic')
if n_iter > 0:
(Q, _) = lu(Q, permute_l=True)
#
# Conduct normalized power iterations.
#
for it in range(n_iter):
cnorm = np.zeros((l), dtype=dtype)
for j in range(l):
cnorm[j] = norm(Q[:, j])
Q = mult(A, Q)
if it + 1 < n_iter:
(Q, _) = lu(Q, permute_l=True)
else:
anorm = 0
for j in range(l):