Compute the trace of a tensor `x`. `trace(x)` returns the sum along the main diagonal of each inner-most matrix in x. If x is of rank `k` with shape `[I, J, K, ..., L, M, N]`, then output is a tensor of rank `k-2` with dimensions `[I, J, K, ..., L]` where `output[i, j, k, ..., l] = trace(x
(x, name=None)
| 2522 | @deprecation.deprecated_endpoints("trace") |
| 2523 | @dispatch.add_dispatch_support |
| 2524 | def trace(x, name=None): |
| 2525 | """Compute the trace of a tensor `x`. |
| 2526 | |
| 2527 | `trace(x)` returns the sum along the main diagonal of each inner-most matrix |
| 2528 | in x. If x is of rank `k` with shape `[I, J, K, ..., L, M, N]`, then output |
| 2529 | is a tensor of rank `k-2` with dimensions `[I, J, K, ..., L]` where |
| 2530 | |
| 2531 | `output[i, j, k, ..., l] = trace(x[i, j, i, ..., l, :, :])` |
| 2532 | |
| 2533 | For example: |
| 2534 | |
| 2535 | ```python |
| 2536 | x = tf.constant([[1, 2], [3, 4]]) |
| 2537 | tf.linalg.trace(x) # 5 |
| 2538 | |
| 2539 | x = tf.constant([[1, 2, 3], |
| 2540 | [4, 5, 6], |
| 2541 | [7, 8, 9]]) |
| 2542 | tf.linalg.trace(x) # 15 |
| 2543 | |
| 2544 | x = tf.constant([[[1, 2, 3], |
| 2545 | [4, 5, 6], |
| 2546 | [7, 8, 9]], |
| 2547 | [[-1, -2, -3], |
| 2548 | [-4, -5, -6], |
| 2549 | [-7, -8, -9]]]) |
| 2550 | tf.linalg.trace(x) # [15, -15] |
| 2551 | ``` |
| 2552 | |
| 2553 | Args: |
| 2554 | x: tensor. |
| 2555 | name: A name for the operation (optional). |
| 2556 | |
| 2557 | Returns: |
| 2558 | The trace of input tensor. |
| 2559 | """ |
| 2560 | with ops.name_scope(name, "Trace", [x]) as name: |
| 2561 | x = ops.convert_to_tensor(x, name="x") |
| 2562 | return reduce_sum(array_ops.matrix_diag_part(x), [-1], name=name) |
| 2563 | |
| 2564 | |
| 2565 | @tf_export("linalg.matmul", "matmul") |
nothing calls this directly
no test coverage detected