Math for AI course · Lesson 17 of 180

Linear Combinations for AI: How Weighted Vectors Build a New Representation

Scale and combine vectors, inspect every coordinate in NumPy, and see why attention outputs are a special kind of weighted representation.

Share this article

An AI system often has several candidate vectors and needs one result. Picking only one candidate would discard the rest. Adding them unchanged would give every candidate the same strength. A linear combination supplies a more flexible operation: scale each vector by its own coefficient, then add the scaled contributions.

For example, two vectors might encode different pieces of context. Coefficients of 0.750.75 and 0.250.25 let the first contribute three times as strongly as the second. The result is still one vector in the same coordinate system, ready for the next computation.

By the end of this lesson, you will be able to construct a linear combination coordinate by coordinate, interpret what each coefficient changes, implement the operation with shape checks in NumPy, and identify the extra conditions that turn a general linear combination into an average-like attention output.

Learning outcome: Construct and interpret a weighted sum of vectors.

Lesson 16: Scalar Multiplication for AI showed how one scalar controls one vector’s strength and direction. Lesson 15 supplied vector addition. This lesson joins those operations. The official Mathematics for Machine Learning companion places scalar and matrix operations in Section 2.2 and defines linear combinations in Section 2.5 of the book. The feature story, calculations, code, visual, and assessments below are original.

Give every candidate its own coefficient

Let v1,v2,…,vk∈Rn\boldsymbol{v}_1,\boldsymbol{v}_2,\ldots,\boldsymbol{v}_k\in\mathbb{R}^n be kk vectors. The notation Rn\mathbb{R}^n means that each vector has nn real coordinates. Let a1,a2,…,ak∈Ra_1,a_2,\ldots,a_k\in\mathbb{R} be real-number coefficients. A coefficient is the scalar assigned to one vector.

Calling this a “weighted sum” describes the same arithmetic: the coefficients are the weights. “Weight” here does not necessarily mean a learned model parameter or a probability. Its role is simply to scale one contribution.

All input vectors must belong to the same vector space for their sum to make sense. In an array calculation, that normally means the same shape and the same coordinate meaning. A two-coordinate vector for [temperature, humidity] cannot be added meaningfully to a two-coordinate vector for [height, age] merely because both have shape (2,).

Track two contributions all the way to the result

Suppose a small representation uses the coordinates [topic, urgency]. Two candidate vectors are

u=[31],v=[−13].\boldsymbol{u}=\begin{bmatrix}3\\1\end{bmatrix}, \qquad \boldsymbol{v}=\begin{bmatrix}-1\\3\end{bmatrix}.

Choose coefficients a=0.75a=0.75 and b=0.25b=0.25. The requested linear combination is r=au+bv\boldsymbol{r}=a\boldsymbol{u}+b\boldsymbol{v}.

This example also shows why “larger coefficient” is not the same as “larger final coordinate.” A coefficient scales a whole vector. The sign and size of each vector coordinate still determine whether that contribution raises or lowers the corresponding result coordinate.

The component rule explains the operation

Write the input vectors by coordinates:

vi=[vi1vi2⋮vin].\boldsymbol{v}_i= \begin{bmatrix} v_{i1}\\v_{i2}\\\vdots\\v_{in} \end{bmatrix}.

The symbol vijv_{ij} means coordinate jj of vector ii. Scaling and addition act coordinate by coordinate, so the result’s coordinate jj is

rj=∑i=1kaivij.r_j=\sum_{i=1}^{k}a_i v_{ij}.

This identity is the reason the two-step recipe works. Scalar multiplication makes contribution ii equal to [aivi1,…,aivin]T[a_i v_{i1},\ldots,a_i v_{in}]^\mathsf{T}. Vector addition then sums all first coordinates to obtain r1r_1, all second coordinates to obtain r2r_2, and so on. Because each coordinate calculation is a real-number calculation, the result again has nn real coordinates.

The same rule gives useful algebraic checks. Regrouping contributions does not change the result because real-number addition is associative. Reordering them does not change it because addition is commutative:

au+bv=bv+au.a\boldsymbol{u}+b\boldsymbol{v} =b\boldsymbol{v}+a\boldsymbol{u}.

That does not mean coefficients can be swapped between vectors. Usually au+bv≠bu+ava\boldsymbol{u}+b\boldsymbol{v}\ne b\boldsymbol{u}+a\boldsymbol{v} because a different vector received each scale.

Move the coefficients, not the coordinate meanings

The explorer fixes u=[3,1]T\boldsymbol{u}=[3,1]^\mathsf{T} and v=[−1,3]T\boldsymbol{v}=[-1,3]^\mathsf{T} while exposing aa and bb. The solid and dashed arrows show the two scaled contributions from the origin. A translated copy of bvb\boldsymbol{v} begins at the tip of aua\boldsymbol{u}, showing the addition path. The dotted result arrow connects the origin directly to their sum.

Interactive linear combination: change two coefficients and follow both scaled contributions to their sum.
Choose the two coefficients

Each range runs from −1.5 to 2 in steps of 0.25. Use the arrow keys for one step, or Page Up and Page Down for larger changes.

Current calculation: a = +0.75, b = +0.25, au = (+2.25, +0.75), bv = (-0.25, +0.75), and r = au + bv = (+2, +1.5).

aubvr = au + bv

Line patterns and labels distinguish all arrows without relying on color. The translated dashed arrow has the same length and direction as bv; moving its starting point shows addition without changing the contribution. If the result is zero, a dotted ring marks the origin.

Numeric alternative for the current coefficients, vectors, contributions, and result
QuantityCoefficientOriginal vectorScaled contribution
First candidate u+0.75(+3, +1)(+2.25, +0.75)
Second candidate v+0.25(-1, +3)(-0.25, +0.75)
Result rNot applicableNot applicable(+2, +1.5)

At the server-rendered starting state, a=0.75a=0.75 and b=0.25b=0.25, so the dotted arrow ends at (2,1.5)(2,1.5), matching the worked example. Set one coefficient to zero and its contribution disappears. Move a coefficient below zero and its arrow reverses. Set both coefficients to zero and every contribution collapses to the zero vector. None of those changes renames or reorders the coordinates.

A linear combination is broader than an average

Several related terms use the same scale-and-add operation but impose different rules on the coefficients.

Combination typeCoefficient conditionsGeometric consequence for two input points
Linear combinationai∈Ra_i\in\mathbb{R}Can move through a whole line or plane generated by the vectors
Affine combination∑iai=1\sum_i a_i=1Stays in the affine line or flat through the input points, but can extend beyond them
Convex combinationai≥0a_i\ge 0 and ∑iai=1\sum_i a_i=1Stays between the inputs or inside their convex hull

In this lesson, weighted average means the common form with normalized nonnegative weights, so it is a convex combination. Some fields use the term “weighted mean” with different conventions, which should be stated explicitly. The starting example qualifies under the convention here because 0.75+0.25=10.75+0.25=1 and both coefficients are nonnegative. In contrast, 1.5u−0.5v1.5\boldsymbol{u}-0.5\boldsymbol{v} is a valid linear and affine combination, but not a convex combination: its negative coefficient can carry the result beyond the segment between the two vectors.

The zero vector is always reachable as a linear combination by setting every coefficient to zero. That fact does not say the inputs are themselves zero. It only says the operation permits the trivial combination with no active contribution.

Attention uses a constrained weighted sum of values

The original Transformer paper defines an attention output as a weighted sum of value vectors. Each value vector is a candidate representation with the same feature dimension. The attention mechanism computes how much each value contributes for the current position, then performs the linear combination. The paper’s scaled dot-product attention equation writes many such sums compactly as a matrix operation.

For a single illustrative output, suppose the already-computed attention weights are 0.60.6, 0.30.3, and 0.10.1, and the value vectors are

x1=[20],x2=[04],x3=[−12].\boldsymbol{x}_1=\begin{bmatrix}2\\0\end{bmatrix},\quad \boldsymbol{x}_2=\begin{bmatrix}0\\4\end{bmatrix},\quad \boldsymbol{x}_3=\begin{bmatrix}-1\\2\end{bmatrix}.

Then the attention-style representation is

z=0.6x1+0.3x2+0.1x3=[1.20]+[01.2]+[−0.10.2]=[1.11.4].\begin{aligned} \boldsymbol{z} &=0.6\boldsymbol{x}_1+0.3\boldsymbol{x}_2+0.1\boldsymbol{x}_3\\ &=\begin{bmatrix}1.2\\0\end{bmatrix} +\begin{bmatrix}0\\1.2\end{bmatrix} +\begin{bmatrix}-0.1\\0.2\end{bmatrix}\\ &=\begin{bmatrix}1.1\\1.4\end{bmatrix}. \end{aligned}

In the paper’s attention operation, the normalization used to produce these weights makes them nonnegative and makes each set sum to one. The final sum is therefore a convex combination of the value vectors for that attention output. Those restrictions belong to this attention mechanism, not to the definition of a linear combination.

This lesson deliberately starts after the weights have been produced. It does not yet teach queries, keys, compatibility scores, normalization, multiple heads, or the later output projection. The durable mathematical point is narrower: once coefficients and compatible value vectors are available, attention builds a representation by scaling each value and adding the contributions.

NumPy should reveal the vector axis

Store the two candidate vectors as rows of one array. The array vectors then has shape (2, 2): two vectors, each with two coordinates. The coefficient array has shape (2,), one coefficient per vector.

import numpy as np

vectors = np.array([
    [3.0, 1.0],   # u
    [-1.0, 3.0],  # v
])
coefficients = np.array([0.75, 0.25])

if vectors.ndim != 2:
    raise ValueError("vectors must have shape (number_of_vectors, coordinates)")
if coefficients.shape != (vectors.shape[0],):
    raise ValueError("need exactly one coefficient per vector")

scaled = coefficients[:, np.newaxis] * vectors
result = scaled.sum(axis=0)

print(scaled)
print(result)

The verified output is

[[ 2.25  0.75]
 [-0.25  0.75]]
[2.  1.5]

coefficients[:, np.newaxis] changes the coefficient shape from (2,) to (2, 1). NumPy can then broadcast one coefficient down each vector row. The official broadcasting rules compare array dimensions from the right and allow dimensions that match or have size one. After multiplication, sum(axis=0) sums down the vector-row axis and preserves the two coordinate columns.

Writing only coefficients * vectors fails for this example: trailing shapes (2,) and (2, 2) happen to align the two coefficients with the coordinate columns, so NumPy returns a plausible-looking array with the wrong meaning. The first row becomes [2.25, 0.25] instead of [2.25, 0.75]. A successful broadcast is not proof that the coefficient axis was correct.

Shape compatibility is necessary but still not sufficient. If one candidate has three coordinates and another has two, there is no single rectangular vectors array of ordinary numeric values to reduce this way. If both have two coordinates but use different feature definitions, the code runs while the result remains semantically invalid. Check both array shape and coordinate meaning.

Coefficients answer “how much,” not “what does this mean?”

Three habits prevent most errors:

  1. Pair every coefficient with a specific vector before calculating.
  2. Scale complete vectors, then add matching coordinates.
  3. State any extra coefficient rule—such as nonnegativity or a sum of one—rather than assuming the phrase “weighted sum” supplies it.

Negative coefficients are not mistakes in a general linear combination. They reverse a contribution. Coefficients larger than one are also valid; they can extend the result beyond the input arrows. Cancellation is possible when contributions point against one another, and a zero coefficient removes a candidate without changing the vector’s shape.

The next prerequisite-safe course step, Lesson 18, organizes numbers into matrices. Lesson 19 will then reveal a matrix–vector product as several weighted sums. Keep the current recipe—pair, scale, add—close at hand; matrix notation will compress it, not replace it. The Math for AI course page keeps the ordered path and published prerequisites together.

Check your understanding

Question 1

Let u = [2, −1]ᵀ and v = [4, 3]ᵀ. Compute 1.5u − 0.5v and interpret the second contribution's sign.

Show the step-by-step solution

Pair the coefficients with their vectors and scale before adding:

1.5u=1.5[2−1]=[3−1.5],1.5\boldsymbol{u} =1.5\begin{bmatrix}2\\-1\end{bmatrix} =\begin{bmatrix}3\\-1.5\end{bmatrix},−0.5v=−0.5[43]=[−2−1.5].-0.5\boldsymbol{v} =-0.5\begin{bmatrix}4\\3\end{bmatrix} =\begin{bmatrix}-2\\-1.5\end{bmatrix}.

Now add matching coordinates:

1.5u−0.5v=[3+(−2)−1.5+(−1.5)]=[1−3].1.5\boldsymbol{u}-0.5\boldsymbol{v} =\begin{bmatrix}3+(-2)\\-1.5+(-1.5)\end{bmatrix} =\begin{bmatrix}1\\-3\end{bmatrix}.

The negative coefficient reverses v\boldsymbol{v} before the addition. It does not mean “subtract only the negative coordinates”; every coordinate of v\boldsymbol{v} is multiplied by −0.5-0.5.

Question 2

Classify each coefficient pair for au + bv: (0.4, 0.6), (1.2, −0.2), and (2, 1). Which are linear, affine, or convex combinations?

Show the step-by-step solution

Every pair contains real coefficients, so all three create linear combinations.

  • For (0.4,0.6)(0.4,0.6), the coefficients sum to 11 and are nonnegative. It is both affine and convex.
  • For (1.2,−0.2)(1.2,-0.2), the coefficients also sum to 11, so it is affine. The negative coefficient prevents it from being convex.
  • For (2,1)(2,1), the coefficients sum to 33, not 11. It is neither affine nor convex, although it remains a valid linear combination.

The classification depends on coefficient constraints, not on the particular coordinates of u\boldsymbol{u} and v\boldsymbol{v}.

Question 3

In the explorer, what must happen to au when a changes from 0.75 to 0 and then to −0.75 while u stays fixed?

Show the step-by-step solution

At a=0.75a=0.75, the contribution is 0.75u=[2.25,0.75]T0.75\boldsymbol{u}=[2.25,0.75]^\mathsf{T}. At a=0a=0,

0u=[00],0\boldsymbol{u}=\begin{bmatrix}0\\0\end{bmatrix},

so the first contribution collapses to the origin and has no direction. At a=−0.75a=-0.75,

−0.75u=[−2.25−0.75].-0.75\boldsymbol{u}=\begin{bmatrix}-2.25\\-0.75\end{bmatrix}.

The final arrow has the same length as the a=0.75a=0.75 contribution but points in the opposite direction. The vector u\boldsymbol{u} and its coordinate meanings did not change; only its coefficient did.

Question 4

An attention-style operation uses weights (0.2, 0.5, 0.3) with values x₁ = [1, 2]ᵀ, x₂ = [3, 0]ᵀ, and x₃ = [−1, 4]ᵀ. Compute the output and explain why it is a convex combination.

Show the step-by-step solution

Calculate the three contributions:

0.2x1=[0.20.4],0.5x2=[1.50],0.3x3=[−0.31.2].0.2\boldsymbol{x}_1=\begin{bmatrix}0.2\\0.4\end{bmatrix},\quad 0.5\boldsymbol{x}_2=\begin{bmatrix}1.5\\0\end{bmatrix},\quad 0.3\boldsymbol{x}_3=\begin{bmatrix}-0.3\\1.2\end{bmatrix}.

Add them coordinate by coordinate:

z=[0.2+1.5−0.30.4+0+1.2]=[1.41.6].\boldsymbol{z} =\begin{bmatrix}0.2+1.5-0.3\\0.4+0+1.2\end{bmatrix} =\begin{bmatrix}1.4\\1.6\end{bmatrix}.

All three weights are nonnegative, and 0.2+0.5+0.3=10.2+0.5+0.3=1. Those two facts make this weighted sum a convex combination of the value vectors. They are extra conditions from the stated attention-style setup, not requirements for every linear combination.

Question 5

A developer tries to combine vectors with shapes (3,) and (2,). Why is the expression invalid, and why would padding the shorter vector with zero not automatically fix the meaning?

Show the step-by-step solution

Vector addition requires matching coordinates. A shape (3,) vector has three coordinate positions, while a shape (2,) vector has only two, so no third coordinate from the second vector exists to add. The intended expression au+bva\boldsymbol{u}+b\boldsymbol{v} is therefore undefined in one shared Rn\mathbb{R}^n as written.

Padding with zero creates matching array shapes, but it silently invents a coordinate claim: it says the shorter vector’s value for the missing third feature is exactly zero. That may be valid only if the encoding specification defines the same third feature and defines absence as zero. Shape repair cannot substitute for compatible coordinate meaning.

Question 6

Why can coefficients * vectors silently weight coordinates instead of vector rows in NumPy, and what explicit reshape fixes the calculation?

Show the step-by-step solution

With vectors.shape == (2, 2) and coefficients.shape == (2,), NumPy compares dimensions from the right. The coefficient length 2 matches the final coordinate dimension 2, so broadcasting applies the two numbers across the columns. The operation succeeds, but coefficient 1 weights coordinate 1 and coefficient 2 weights coordinate 2.

Insert a size-one coordinate dimension:

scaled = coefficients[:, np.newaxis] * vectors
result = scaled.sum(axis=0)

Now coefficients[:, np.newaxis].shape == (2, 1). The first dimension pairs one coefficient with each vector row, and the size-one dimension broadcasts that coefficient across every coordinate in its row. Summing axis 0 then adds the scaled rows coordinate by coordinate.

Question 7

Show coordinate by coordinate that a(u + v) = au + av for two vectors u, v ∈ ℝ².

Show the step-by-step solution

Write u=[u1,u2]T\boldsymbol{u}=[u_1,u_2]^\mathsf{T} and v=[v1,v2]T\boldsymbol{v}=[v_1,v_2]^\mathsf{T}. The left side is

a(u+v)=a[u1+v1u2+v2]=[a(u1+v1)a(u2+v2)].a(\boldsymbol{u}+\boldsymbol{v}) =a\begin{bmatrix}u_1+v_1\\u_2+v_2\end{bmatrix} =\begin{bmatrix}a(u_1+v_1)\\a(u_2+v_2)\end{bmatrix}.

Real-number distributivity gives

[au1+av1au2+av2]=[au1au2]+[av1av2]=au+av.\begin{bmatrix}au_1+av_1\\au_2+av_2\end{bmatrix} =\begin{bmatrix}au_1\\au_2\end{bmatrix} +\begin{bmatrix}av_1\\av_2\end{bmatrix} =a\boldsymbol{u}+a\boldsymbol{v}.

The first coordinates agree, and the second coordinates agree, so the two vectors are equal. The same argument works for any finite number of coordinates.

Question 8

A model has compatible vectors u and v. Compare r = 2u + 0v with concatenating u and v. What information and shape does each operation produce?

Show the step-by-step solution

The linear combination first scales and then adds:

r=2u+0v=2u.\boldsymbol{r}=2\boldsymbol{u}+0\boldsymbol{v}=2\boldsymbol{u}.

If u,v∈Rn\boldsymbol{u},\boldsymbol{v}\in\mathbb{R}^n, the result remains in Rn\mathbb{R}^n. Vector v\boldsymbol{v} contributes nothing because its coefficient is zero, while every coordinate of u\boldsymbol{u} is doubled.

Concatenation does not add matching coordinates. It places all nn coordinates of u\boldsymbol{u} beside all nn coordinates of v\boldsymbol{v}, producing a 2n2n-coordinate object. Concatenation preserves both input blocks and changes the shape; the linear combination merges their scaled contributions into the original coordinate space. They answer different representation questions.

Sources

  1. Mathematics for Machine Learning companion website
  2. Mathematics for Machine Learning book PDF
  3. Attention Is All You Need
  4. NumPy documentation: numpy.sum
  5. NumPy documentation: broadcasting