-
Notifications
You must be signed in to change notification settings - Fork 5
/
linear_algebra.py
664 lines (489 loc) · 15.4 KB
/
linear_algebra.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
import logging
from typing import Optional, Union
from . import dispatch, B
from .types import Numeric, Int
from .util import abstract
__all__ = [
"epsilon",
"transpose",
"t",
"T",
"matmul",
"mm",
"dot",
"einsum",
"kron",
"trace",
"svd",
"eig",
"solve",
"inv",
"pinv",
"det",
"logdet",
"expm",
"logm",
"cholesky",
"chol",
"cholesky_solve",
"cholsolve",
"triangular_solve",
"trisolve",
"toeplitz_solve",
"toepsolve",
"outer",
"reg",
"pw_dists2",
"pw_dists",
"ew_dists2",
"ew_dists",
"pw_sums2",
"pw_sums",
"ew_sums2",
"ew_sums",
]
log = logging.getLogger(__name__)
epsilon = 1e-12 #: Magnitude of diagonal to regularise matrices with.
def _default_perm(a):
rank_a = B.rank(a)
perm = list(range(rank_a))
# Switch the last two dimensions if `rank_a >= 2`.
if len(perm) >= 2:
perm[-2], perm[-1] = perm[-1], perm[-2]
return perm
@dispatch
@abstract()
def transpose(
a: Numeric, perm: Optional[Union[tuple, list]] = None
): # pragma: no cover
"""Transpose a matrix.
Args:
a (tensor): Matrix to transpose.
perm (list[int] or tuple[int], optional): Permutation. Defaults to
switching the last two axes.
Returns:
tensor: Transposition of `a`.
"""
t = transpose #: Shorthand for `transpose`.
T = transpose #: Shorthand for `transpose`.
@dispatch
@abstract(promote=2)
def matmul(a, b, tr_a: bool = False, tr_b: bool = False): # pragma: no cover
"""Matrix multiplication.
Args:
a (tensor): First matrix.
b (tensor): Second matrix.
tr_a (bool, optional): Transpose first matrix. Defaults to `False`.
tr_b (bool, optional): Transpose second matrix. Defaults to `False`.
Returns:
tensor: Matrix product of `a` and `b`.
"""
mm = matmul #: Shorthand for `matmul`.
dot = matmul #: Shorthand for `matmul`.
@dispatch
@abstract(promote_from=1)
def einsum(equation: str, *elements: Numeric): # pragma: no cover
"""Tensor contraction via Einstein summation.
Args:
equation (str): Equation.
*elements (tensor): Tensors to contract.
Returns:
tensor: Contraction.
"""
@dispatch
@abstract()
def trace(a: Numeric, axis1: Int = -2, axis2: Int = -1): # pragma: no cover
"""Compute the trace of a tensor.
Args:
a (tensor): Tensor to compute trace of.
axis1 (int, optional): First dimension to compute trace over. Defaults
to `-2`.
axis2 (int, optional): Second dimension to compute trace over. Defaults
to `-1`.
Returns:
tensor: Trace.
"""
@dispatch
@abstract(promote=2)
def kron(a, b, *indices: Int):
"""Kronecker product.
Args:
a (tensor): First matrix.
b (tensor): Second matrix.
*indices (int): Indices to compute the Kronecker product over. Defaults to all
indices.
Returns:
tensor: Kronecker product of `a` and `b`.
"""
@dispatch
def kron(a: Numeric, b: Numeric, *indices: Int):
a_shape = B.shape(a)
b_shape = B.shape(b)
if len(a_shape) != len(b_shape):
raise ValueError(
"Can only compute Kronecker products between tensors of equal ranks."
)
# Default to computing the Kronecker product over all indices.
if indices == ():
indices = range(len(a_shape))
else:
# Ensure that all indices are positive indices. Otherwise, the `i in indices`
# below will fail.
indices = [len(a_shape) + i if i < 0 else i for i in indices]
a_indices = ()
b_indices = ()
target_shape = ()
for i in range(len(a_shape)):
if i in indices:
a_indices += (slice(None), None)
b_indices += (None, slice(None))
target_shape += (a_shape[i] * b_shape[i],)
else:
a_indices += (slice(None),)
b_indices += (slice(None),)
if a_shape[i] == b_shape[i]:
target_shape += (a_shape[i],)
else:
raise ValueError(
f"Shape of inputs differ at dimension {i}: "
f"{a_shape[i]} versus {b_shape[i]}."
)
return B.reshape(B.multiply(a[a_indices], b[b_indices]), *target_shape)
@dispatch
@abstract()
def svd(a: Numeric, compute_uv: bool = True): # pragma: no cover
"""Compute the singular value decomposition.
Args:
a (tensor): Matrix to decompose.
compute_uv (bool, optional): Also compute `U` and `V`. Defaults to
`True`.
Returns:
tuple: `(U, S, V)` if `compute_uv` is `True` and just `S` otherwise.
"""
@dispatch
@abstract()
def eig(a: Numeric, compute_eigvecs: bool = True): # pragma: no cover
"""Compute the eigenvalue decomposition.
Args:
a (tensor): Matrix to decompose.
compute_eigvecs (bool, optional): Also compute eigenvectors. Defaults to `True`.
Returns:
tuple: `(S, V)` if `compute_eigvecs` is `True` and just `S` otherwise.
"""
@dispatch
@abstract(promote=2)
def solve(a, b): # pragma: no cover
"""Solve the linear system `a x = b`.
Args:
a (tensor): LHS `a`.
b (tensor): RHS `b`.
Returns:
tensor: Solution `x`.
"""
@dispatch
@abstract()
def inv(a): # pragma: no cover
"""Compute the inverse of `a`.
Args:
a (tensor): Matrix to compute inverse of.
Returns:
tensor: Inverse of `a`.
"""
@dispatch
def pinv(a):
"""Compute the pseudo-inverse of `a`.
Args:
a (tensor): Matrix to compute pseudo-inverse of.
Returns:
tensor: Pseudo-inverse of `a`.
"""
if B.shape(a, -2) >= B.shape(a, -1):
chol = B.chol(B.matmul(a, a, tr_a=True))
return B.cholsolve(chol, B.transpose(a))
else:
chol = B.chol(B.matmul(a, a, tr_b=True))
return B.transpose(B.cholsolve(chol, a))
@dispatch
@abstract()
def det(a): # pragma: no cover
"""Compute the determinant of `a`.
Args:
a (tensor): Matrix to compute determinant of.
Returns:
scalar: Determinant of `a`
"""
@dispatch
@abstract()
def logdet(a): # pragma: no cover
"""Compute the log-determinant of `a`.
Args:
a (tensor): Matrix to compute log-determinant of.
Returns:
scalar: Log-determinant of `a`
"""
@dispatch
@abstract()
def expm(a): # pragma: no cover
"""Compute the matrix exponential of `a`.
Args:
a (tensor): Matrix to matrix exponential of.
Returns:
scalar: Matrix exponential of `a`
"""
@dispatch
@abstract()
def logm(a): # pragma: no cover
"""Compute the matrix logarithm of `a`.
Args:
a (tensor): Matrix to matrix logarithm of.
Returns:
scalar: Matrix logarithm of `a`
"""
@dispatch
def cholesky(a: Numeric):
"""Compute the Cholesky decomposition. The matrix will automatically be regularised
because computing the decomposition.
Args:
a (tensor): Matrix to decompose.
Returns:
tensor: Cholesky decomposition.
"""
return _cholesky(reg(a))
chol = cholesky #: Shorthand for `cholesky`.
@dispatch
@abstract()
def _cholesky(a: Numeric): # pragma: no cover
pass
@dispatch
@abstract(promote=2)
def cholesky_solve(a, b): # pragma: no cover
"""Solve the linear system `a x = b` given the Cholesky factorisation of
`a`.
Args:
a (tensor): Cholesky factorisation of `a`.
b (tensor): RHS `b`.
Returns:
tensor: Solution `x`.
"""
cholsolve = cholesky_solve #: Shorthand for `cholesky_solve`.
@dispatch
@abstract(promote=2)
def triangular_solve(a, b, lower_a: bool = True): # pragma: no cover
"""Solve the linear system `a x = b` where `a` is triangular.
Args:
a (tensor): Triangular matrix `a`.
b (tensor): RHS `b`.
lower_a (bool, optional): Indicate that `a` is lower triangular
instead of upper triangular. Defaults to `True`.
Returns:
tensor: Solution `x`.
"""
trisolve = triangular_solve #: Shorthand for `triangular_solve`.
@dispatch
@abstract(promote=3)
def toeplitz_solve(a, b, c): # pragma: no cover
"""Solve the linear system `toep(a, b) x = c` where `toep(a, b)` is a
Toeplitz matrix.
Args:
a (tensor): First column of the Toeplitz matrix.
b (tensor, optional): *Except for the first element*, first row of the
Toeplitz matrix. Defaults to `a[1:]`.
c (tensor): RHS `c`.
Returns:
tensor: Solution `x`.
"""
@dispatch
def toeplitz_solve(a, c):
return toeplitz_solve(a, a[1:], c)
toepsolve = toeplitz_solve #: Shorthand for `toeplitz_solve`.
def _a_b_uprank(a, b):
a = B.uprank(a)
b = B.uprank(b)
return a, b
@dispatch
def outer(a, b):
"""Compute the outer product between two vectors or matrices.
Args:
a (tensor): First tensor.
b (tensor): Second tensor.
Returns:
tensor: Outer product of `a` and `b`.
"""
a, b = _a_b_uprank(a, b)
# Optimise the case that both are column vectors.
if B.shape(a, -1) == 1 and B.shape(b, -1) == 1:
return a * B.transpose(b)
return B.matmul(a, b, tr_b=True)
@dispatch
def outer(a):
return outer(a, a)
@dispatch
def reg(a, diag=None, clip: bool = True):
"""Add a diagonal to a matrix.
Args:
a (matrix): Matrix to add a diagonal to.
diag (float, optional): Magnitude of the diagonal to add. Defaults to
`.linear_algebra.epsilon`.
clip (bool, optional): Let `diag` be at least `.linear_algebra.epsilon`.
Defaults to `True`.
Returns:
matrix: Regularised version of `a`.
"""
# Careful to use `B.epsilon` here and not `epsilon`! Otherwise, changes
# will not be tracked.
if diag is None:
diag = B.epsilon
if clip and diag is not B.epsilon:
diag = B.maximum(diag, B.epsilon)
return a + diag * B.eye(a)
@dispatch
def pw_dists2(a, b):
"""Compute the square the Euclidean norm of the pairwise differences between two
matrices where rows correspond to elements and columns to features.
Args:
a (matrix): First matrix.
b (matrix, optional): Second matrix. Defaults to `a`.
Returns:
matrix: Square of the Euclidean norm of the pairwise differences
between the elements of `a` and `b`.
"""
a, b = _a_b_uprank(a, b)
# Optimise the one-dimensional case.
if B.shape(a, -1) == 1 and B.shape(b, -1) == 1:
return (a - B.transpose(b)) ** 2
norms_a = B.sum(a ** 2, axis=-1)[..., :, None]
norms_b = B.sum(b ** 2, axis=-1)[..., None, :]
return norms_a + norms_b - 2 * B.matmul(a, b, tr_b=True)
@dispatch
def pw_dists2(a):
return pw_dists2(a, a)
@dispatch
def pw_dists(a, b):
"""Compute the Euclidean norm of the pairwise differences between two matrices
where rows correspond to elements and columns to features.
Args:
a (matrix): First matrix.
b (matrix, optional): Second matrix. Defaults to `a`.
Returns:
matrix: Euclidean norm of the pairwise differences between the
elements of `a` and `b`.
"""
a, b = _a_b_uprank(a, b)
# Optimise the one-dimensional case.
if B.shape(a, -1) == 1 and B.shape(b, -1) == 1:
return B.abs(a - B.transpose(b))
return B.sqrt(B.maximum(B.pw_dists2(a, b), B.cast(B.dtype(a), 1e-30)))
@dispatch
def pw_dists(a):
return pw_dists(a, a)
@dispatch
def ew_dists2(a, b):
"""Compute the square the Euclidean norm of the element-wise differences between
two matrices where rows correspond to elements and columns to features.
Args:
a (matrix): First matrix.
b (matrix, optional): Second matrix. Defaults to `a`.
Returns:
matrix: Square of the Euclidean norm of the element-wise differences
between the elements of `a` and `b`.
"""
a, b = _a_b_uprank(a, b)
return B.sum((a - b) ** 2, axis=-1)[..., :, None]
@dispatch
def ew_dists2(a):
return ew_dists2(a, a)
@dispatch
def ew_dists(a, b):
"""Compute the Euclidean norm of the element-wise differences between two
matrices where rows correspond to elements and columns to features.
Args:
a (matrix): First matrix.
b (matrix, optional): Second matrix. Defaults to `a`.
Returns:
matrix: Euclidean norm of the element-wise differences between the
elements of `a` and `b`.
"""
a, b = _a_b_uprank(a, b)
# Optimise the one-dimensional case.
if B.shape(a, -1) == 1 and B.shape(b, -1) == 1:
return B.abs(a - b)
return B.sqrt(B.maximum(B.ew_dists2(a, b), B.cast(B.dtype(a), 1e-30)))
@dispatch
def ew_dists(a):
return ew_dists(a, a)
@dispatch
def pw_sums2(a, b):
"""Compute the square the Euclidean norm of the pairwise sums between two
matrices where rows correspond to elements and columns to features.
Args:
a (matrix): First matrix.
b (matrix, optional): Second matrix. Defaults to `a`.
Returns:
matrix: Square of the Euclidean norm of the pairwise sums
between the elements of `a` and `b`.
"""
a, b = _a_b_uprank(a, b)
# Optimise the one-dimensional case.
if B.shape(a, -1) == 1 and B.shape(b, -1) == 1:
return (a + B.transpose(b)) ** 2
norms_a = B.sum(a ** 2, axis=-1)[..., :, None]
norms_b = B.sum(b ** 2, axis=-1)[..., None, :]
return norms_a + norms_b + 2 * B.matmul(a, b, tr_b=True)
@dispatch
def pw_sums2(a):
return pw_sums2(a, a)
@dispatch
def pw_sums(a, b):
"""Compute the Euclidean norm of the pairwise sums between two
matrices where rows correspond to elements and columns to features.
Args:
a (matrix): First matrix.
b (matrix, optional): Second matrix. Defaults to `a`.
Returns:
matrix: Euclidean norm of the pairwise sums between the
elements of `a` and `b`.
"""
a, b = _a_b_uprank(a, b)
# Optimise the one-dimensional case.
if B.shape(a, -1) == 1 and B.shape(b, -1) == 1:
return B.abs(a + B.transpose(b))
return B.sqrt(B.maximum(B.pw_sums2(a, b), B.cast(B.dtype(a), 1e-30)))
@dispatch
def pw_sums(a):
return pw_sums(a, a)
@dispatch
def ew_sums2(a, b):
"""Compute the square the Euclidean norm of the element-wise
sums between two matrices where rows correspond to elements and
columns to features.
Args:
a (matrix): First matrix.
b (matrix, optional): Second matrix. Defaults to `a`.
Returns:
matrix: Square of the Euclidean norm of the element-wise sums
between the elements of `a` and `b`.
"""
a, b = _a_b_uprank(a, b)
return B.sum((a + b) ** 2, axis=-1)[..., :, None]
@dispatch
def ew_sums2(a):
return ew_sums2(a, a)
@dispatch
def ew_sums(a, b):
"""Compute the Euclidean norm of the element-wise sums between two
matrices where rows correspond to elements and columns to features.
Args:
a (matrix): First matrix.
b (matrix, optional): Second matrix. Defaults to `a`.
Returns:
matrix: Euclidean norm of the element-wise sums between the
elements of `a` and `b`.
"""
a, b = _a_b_uprank(a, b)
# Optimise the one-dimensional case.
if B.shape(a, -1) == 1 and B.shape(b, -1) == 1:
return B.abs(a + b)
return B.sqrt(B.maximum(B.ew_sums2(a, b), B.cast(B.dtype(a), 1e-30)))
@dispatch
def ew_sums(a):
return ew_sums(a, a)