Lawfare Group → Knowledge Institute → Lawfare Academy
← CS 230 — Mathematics, Statistics and Data for AI
Weeks 1–2
Vectors, matrices and dimensional reasoning
Learning objectives
- Explain and trace the mechanisms in vectors, matrices and dimensional reasoning.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.
A vector is an ordered collection of components; a matrix can represent a collection of observations or a linear transformation. Meaning depends on the declared axes. If X has n rows and d columns, rows may be observations and columns features. Multiplying X by a d-component coefficient vector produces n predictions. A dimension mismatch often reveals a conceptual mistake before code runs.
A dot product sums componentwise products. For a linear model it combines features with weights, but the units matter. A weight multiplying hours differs from a weight multiplying dollars. Feature scaling changes coefficient interpretation and can affect optimization. Broadcasting is a programming convenience that expands compatible dimensions implicitly; it can create a numerically valid but unintended calculation. Never use successful execution as proof that shapes mean what you intended.
Linear independence concerns whether one vector can be built from others. Redundant features can make coefficient estimation unstable or nonunique even if predictions remain similar. Matrix multiplication is generally not commutative. Track the interpretation of AB rather than assuming BA describes the same process. Begin with tiny hand calculations and verify them in code before using large tensors.
Worked reasoning Two hours at weight 10 and three visits at weight 5 contribute 20 and 15, giving 35 in the model’s output units. zip alone would silently truncate unequal inputs, so the explicit length check is part of correctness. The function computes a mathematical operation, not a fitted or validated prediction system.
Extended teaching and laboratory
A matrix product is meaningful when both dimensions and represented units align. Shape compatibility prevents one class of error but cannot establish that features are in the correct order or measured in the intended units. A dot product silently using dollars against a coefficient trained for cents can be numerically valid and semantically wrong.
Keep a feature schema alongside the parameters. Batch rows represent observations; columns represent features in an explicit order. A bias term is an additional model component, not a reason to ignore units.
Worked problem Two jobs have features [hours,visits]: [2,3] and [4,1]. The coefficient vector is [1000 cents/hour,500 cents/visit], with bias 200 cents. Compute predictions and dimensions.
Step-by-step reasoning 1. X has shape 2×2 and w has shape 2×1. Xw has shape 2×1, one prediction per job.
- The first dot product is 2000+1500=3500 cents; the second is 4000+500=4500 cents.
- Add the 200-cent bias to each result: 3700 and 4700 cents. The bias is not multiplied by the number of features.
- Record feature order and units. Swapping hours and visits produces a different model even though the array dimensions still match.
From arrays to transformations, geometry and identifiable parameters
A feature table is an array with a declared meaning. A scalar has no array axis, a vector has one, and a matrix has two. Higher-order tensors add axes: a batch of color images might use [image, height, width, channel]. An array's order counts its axes; the length of an axis counts entries along that axis. Write these names beside the shape. A three-channel image does not become three independent customers because its first array dimension happens to be three.
Two operations that look like multiplication answer different questions. Elementwise multiplication pairs corresponding entries and retains their shape. A matrix product contracts a shared dimension: for A of shape m×d and B of shape d×p, C=AB has shape m×p and C[i,j]=Σk A[i,k]B[k,j]. Each entry is a row–column dot product. The shared dimension must represent compatible quantities, not merely have an equal integer length. The transpose exchanges indices, Aᵀ[j,i]=A[i,j]; it changes the role of rows and columns. Consequently (AB)ᵀ=BᵀAᵀ. Reversing multiplication generally changes the transformation.
For an original fictional workload, let A=[[1,2],[3,4]] describe two jobs' demands for two resources, and B=[[2,0],[1,3]] describe two alternative resource-price schedules. AB=[[4,6],[10,12]] gives each job's charge under each schedule. BA=[[2,4],[10,14]] is mathematically defined but combines different axes and does not answer the price question. A's elementwise square is [[1,4],[9,16]], whereas A²=[[7,10],[15,22]]. Neither can substitute for the other.
A reduction removes an axis by summing its entries. A's column totals are [4,6], its row totals are [3,7], and its grand total is 10. Dividing each row by its own total gives [1/3,2/3] and [3/7,4/7]. Preserve a singleton column for row totals when a library broadcasts division across columns; a bare vector can align with the wrong axis or fail depending on shape. These normalized values are resource shares, not probabilities of a successful job unless a separate model justifies that interpretation.
Length, angle, projection and independent information
The Euclidean norm ||x||₂=√Σxᵢ² measures length; ||x||₁=Σ|xᵢ| adds absolute components. For x=[3,4], the values are 5 and 7. The Frobenius norm of a matrix applies the square-root-of-squared-entries calculation to all entries. A norm is nonnegative, zero only at the zero vector, scales by |a| under multiplication by a, and obeys the triangle inequality. Norms measure mathematical magnitudes in the chosen coordinates. Adding a dollar component to an hour component without a declared scaling does not create a meaningful physical length.
For nonzero vectors, cos θ=(x·y)/(||x||₂||y||₂). Orthogonal vectors have dot product zero. With u=[1,0], the projection of x=[3,4] onto u is [(x·u)/(u·u)]u=[3,0], leaving residual [0,4], orthogonal to u. A projection retains one direction and discards the perpendicular component. Dividing by u·u is undefined for the zero vector. A larger projection does not establish a causal relationship or permission to use a feature.
Columns are linearly independent when no nonzero coefficient combination gives the zero vector. The column rank counts independent directions; the null space contains coefficient changes that leave the product unchanged. In X=[[1,2],[2,4]], column 2 is twice column 1. Xβ depends only on β₁+2β₂. Both β=[2,0] and [0,1] predict [2,4]; adding any multiple of [-2,1] leaves predictions unchanged. There is no uniquely identified pair of coefficients. Inverting XᵀX cannot repair this: it is singular. Nearly dependent columns can also amplify rounding or small measurement changes. Use established numerical solvers and inspect conditioning; successful calculation is not identification.
A linear map is determined by its action on a basis: its jth column is the image of the jth coordinate unit vector. For M=[[2,1],[0,3]], a vector [x,y] becomes x[2,0]+y[1,3]. It stretches and shears coordinates without introducing a location-dependent nonlinear rule. Its determinant is 2×3−1×0=6. This scales ordinary area by |6| and preserves orientation. A negative determinant reverses orientation; ordinary area uses its absolute value. For a square [[a,b],[c,d]], a nonzero determinant ad−bc permits inverse (1/(ad−bc))[[d,−b],[−c,a]]. Thus M⁻¹=[[1/2,−1/6],[0,1/3]]; multiplying in either order yields the identity. Independent columns in a rectangular matrix give an injective map onto its image, not necessarily a two-sided square inverse. Solving a system with a numerical solver generally avoids forming an explicit inverse.
A hyperplane w·x=b with nonzero w separates two half-spaces according to the sign of w·x−b. Its normal is w; signed perpendicular distance is (w·x−b)/||w||₂. For w=[2,1], b=4 and x=[1,3], the score is 1 and signed distance is 1/√5. A score's numerical size changes when both w and b are multiplied by a positive constant, while the boundary and distance remain unchanged. A separating boundary is a decision rule, not evidence of causal identification or held-out predictive performance.
Tensor contraction extends the same sum-of-products rule to named axes. If H[i,j,k] has shape 2×3×4 and W[j,k] has shape 3×4, Y[i]=ΣjΣk H[i,j,k]W[j,k] has shape 2. Here j and k are summed indices, and i remains free. Einstein notation often suppresses an explicitly understood repeated-index sum; an einsum string makes the output indices explicit. For a square matrix, trace(A)=Σi A[i,i] sums its diagonal and differs from summing every entry. Check an expression's free indices and shapes before translating it into library syntax. A contraction can be numerically correct while contracting the wrong semantic axes.
Eigenvectors and the limits of repeated transformations
For a square matrix A, an eigenvector is a
nonzero
vector v satisfying Av=λv. Positive λ scales its direction, negative λ reverses it, and zero λ sends it to zero. Solve det(A−λI)=0 for eigenvalues, then solve (A−λI)v=0 for their eigenspaces. Multiples of an eigenvector remain eigenvectors; software can normalize or reverse signs without changing the eigendirection.
Take the new symmetric matrix S=[[3,1],[1,3]]. Its characteristic equation is (3−λ)²−1=0, giving λ=4 and 2. Direct products verify S[1,1]=4[1,1] and S[1,−1]=2[1,−1]. Normalize these vectors by √2 to form orthogonal columns Q. Then S=Q diag(4,2) Qᵀ; Qᵀ=Q⁻¹. This expresses a change of coordinates, two independent scalings, and a return to the original coordinates. Symmetric real matrices admit such an orthonormal eigenbasis. A general matrix need not.
If a full independent eigenbasis exists, A=VΛV⁻¹ and Aⁿ=VΛⁿV⁻¹. For S and starting x=[2,0]=[1,1]+[1,−1], Sⁿx=4ⁿ[1,1]+2ⁿ[1,−1]. At n=2 this is [20,12]. The direction increasingly follows [1,1] because its component grows faster. Starting instead at [1,−1] leaves the dominant component exactly zero, so iteration stays in that direction. A unique dominant eigenvalue in absolute value, nonzero starting projection and appropriate matrix structure matter for a power-iteration explanation. Equal-modulus eigenvalues, rotations and defective matrices defeat a blanket alignment claim.
For J=[[1,1],[0,1]], the only eigendirection is [1,0], although it contains infinitely many nonzero eigenvectors. J is not diagonalizable. Jⁿ=[[1,n],[0,1]], so applying it to [0,1] produces [n,1]: growth occurs even though both eigenvalues equal one. Likewise N=[[0,1],[0,0]] has rank one but both eigenvalues zero. Thus rank does not generally equal the number of nonzero eigenvalues; that shortcut applies in the diagonalizable setting. Spectral-radius scaling alone does not guarantee unchanged norms at every iteration or stable behavior of an entire nonlinear network.
Gershgorin bounds give a useful check before solving: each eigenvalue lies in at least one complex disc centered at a diagonal entry, with radius the sum of the absolute off-diagonal entries in that row. For S, both discs center on 3 with radius 1. Symmetry makes the eigenvalues real, so they lie in [2,4], consistent with the exact calculation. A bound supplies a region, not an exact eigenvalue or a guarantee that each overlapping disc contains one distinct eigenvalue.
Optional changed record: transform, project and test an overclaim
Replace S with T=[[2,1],[1,2]], and use x=[3,1]. Compute eigenpairs and T²x. Project x onto the unit dominant direction. A colleague says that dividing T by its largest eigenvalue preserves every vector's length and therefore certifies stable training. Evaluate the statement. Also give two different coefficient vectors producing Xβ=[3,6] for the singular X above.
The eigenvalues are 3 and 1, with directions [1,1] and [1,−1]. Decompose x=2[1,1]+[1,−1]. Therefore T²x=18[1,1]+[1,−1]=[19,17]; direct multiplication gives Tx=[7,5] and T[7,5]=[19,17]. The unit dominant direction is q=[1,1]/√2. Its coefficient q·x=4/√2=2√2 gives projection (q·x)q=[2,2], residual [1,−1], and squared lengths 8+2=10=||x||₂².
T/3 preserves the dominant direction's length but shrinks the orthogonal direction by 1/3. On x it gives [7/3,5/3], whose squared norm is 74/9, below the original 10. This disproves universal length preservation; it also says nothing by itself about a nonlinear network's loss, data or training procedure. For X, β=[3,0] and [1,1] both satisfy β₁+2β₂=3 and predict [3,6]. Their difference [-2,1] lies in the null space. A software answer selecting one pair needs an explicit selection rule; it does not make the two coefficients uniquely identified by the observations.
Optional evidence criteria: (1) show dimensions and independently check a row–column product; (2) compute projection and verify orthogonality; (3) verify both eigenpairs and changed-record matrix powers; (4) distinguish an identity valid under stated assumptions from a false universal claim, using a numerical counterexample. Give one point for each fully explained criterion. This practice is independent study, not an observed competency assessment.
Apply the idea
Two jobs have features [hours,visits]: [2,3] and [4,1]. The coefficient vector is [1000 cents/hour,500 cents/visit], with bias 200 cents. Compute predictions and dimensions.
The hours feature is converted to minutes. What coefficient preserves the same prediction, and what error occurs if the old coefficient is retained?
Read the worked reasoning
Divide the hours coefficient by 60: 1000/60 cents per minute. Then 120 minutes contributes the same 2000 cents as two hours. Retaining 1000 as cents per minute inflates that contribution by a factor of 60. Matching dimensions alone will not detect the unit error.
Check understanding
Why label matrix dimensions before implementing a model?
- To check whether each operation matches its intended meaning
Feedback
Shape reasoning catches many representation errors early.
- Because matching shapes guarantee a good model
Feedback
Mathematically compatible shapes can still encode the wrong task.
- To eliminate all numerical error
Feedback
Finite precision remains a separate numerical issue.
Further reading
Current study directions: use the original Academy preparation chapters, preserved teaching and complete optional worked reasoning on LawfareGroup.com. Retained attributed readings, source exercises and historical assignment directions are optional further study. This notice supersedes earlier textbook-supported directions preserved below and in historical companions. Independent subject review and observed learner testing remain pending.
Read the original on-site preparation chapter and preserved investigation. Work the changed record before opening its full model. Earlier source assignment directions remain in immutable edition4.
- Original on-site preparation — From arrays to transformations, geometry and identifiable parameters
- Dive into Deep Learning
- 2.3. Linear Algebra Open the notebook in SageMaker Studio Lab
- 22.1. Geometry and Linear Algebraic Operations Open the notebook in SageMaker Studio Lab
- 22.2. Eigendecompositions Open the notebook in SageMaker Studio Lab