TensorFlow
Matrix Operations
Diagonal Extraction
Machine Learning
Python Libraries

Get the diagonal of a matrix in TensorFlow

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Extracting matrix diagonals in TensorFlow is straightforward with dedicated ops, but confusion arises with batched tensors and non-square shapes. Using the right diagonal function avoids manual indexing bugs and keeps operations differentiable and efficient. This article covers common diagonal extraction patterns.

Core Sections

1. Basic diagonal extraction

python
1import tensorflow as tf
2
3m = tf.constant([[1, 2, 3],
4                 [4, 5, 6],
5                 [7, 8, 9]])
6
7d = tf.linalg.diag_part(m)
8print(d.numpy())  # [1 5 9]

diag_part returns main diagonal.

2. Batched matrices

python
1b = tf.constant([
2    [[1, 2], [3, 4]],
3    [[5, 6], [7, 8]],
4])
5
6print(tf.linalg.diag_part(b).numpy())
7# [[1 4], [5 8]]

Works across leading batch dimensions.

3. Creating diagonal matrix from vector

python
v = tf.constant([1., 2., 3.])
D = tf.linalg.diag(v)

Inverse operation of extracting diagonal (for simple rank).

4. Non-square matrices

For shape (m, n), diagonal length is min(m, n).

python
x = tf.ones((2, 4))
print(tf.linalg.diag_part(x).shape)  # (2,)

5. Gradient flow

Diagonal ops are differentiable and compatible with GradientTape, useful in custom losses/regularization.

6. Performance notes

Prefer built-in diagonal ops over Python loops or tf.gather_nd manual indexing unless you need custom diagonals/off-diagonals.

Validation and production readiness

A solution that works once in a local test is not enough for long-term reliability. Add explicit validation around inputs, outputs, and failure paths so behavior remains predictable after refactors. Start with a compact test matrix that covers expected inputs, boundary values, malformed values, and one realistic load scenario. This catches most regressions before they reach runtime environments where debugging is slower and costlier.

When external dependencies are involved, verify the unhappy path intentionally. Simulate missing files, network timeouts, permission errors, and unavailable services. The goal is to confirm the code fails in a controlled, observable way. Silent failure, broad exception swallowing, and unbounded retries are frequent causes of production incidents. Prefer explicit failure states and bounded retry policies.

text
1reliability_checklist:
2  - happy path tested with representative data
3  - boundary and malformed cases tested
4  - timeouts and retries are bounded
5  - dependency failures produce clear errors
6  - logs and metrics expose outcome and latency

Observability should be designed into the implementation, not added later. Emit structured logs for key branch decisions and final outcomes. Include identifiers and context needed for triage, but avoid sensitive payloads. For asynchronous or multi-step flows, add correlation IDs so related events can be traced end-to-end. If the workflow is performance sensitive, record duration metrics and establish rough service-level thresholds.

Configuration discipline is equally important. Keep environment-specific values (paths, credentials, endpoints, feature flags) outside code and validate them at startup. Fail fast on invalid configuration rather than partially starting with broken defaults. In team settings, document required runtime versions and compatibility constraints near the code so local, CI, and production environments behave consistently.

Before shipping, run a lightweight rollout checklist that includes backward compatibility, rollback strategy, and smoke verification steps. For data or schema changes, include idempotency checks so reruns do not create duplicates or corruption. Teams that standardize these practices usually spend less time on repeated incident triage and more time delivering reliable improvements.

Common Pitfalls

  • Confusing diag (construct) with diag_part (extract).
  • Misunderstanding output shape for batched inputs.
  • Assuming non-square matrices produce full-length row/col outputs.
  • Using slow manual indexing for simple diagonal operations.
  • Ignoring dtype consistency when combining with other tensors.

Summary

Use tf.linalg.diag_part to extract matrix diagonals and tf.linalg.diag to construct diagonal matrices. These ops support batched tensors, remain differentiable, and are more reliable than manual indexing patterns.

Documenting these conventions in team runbooks and enforcing quick CI checks helps keep behavior consistent as codebases and environments evolve.


Course illustration
Course illustration