Skip to main content\(\newcommand{\N}{\mathbb{N}}
\newcommand{\Z}{\mathbb{Z}}
\newcommand{\Q}{\mathbb{Q}}
\newcommand{\R}{\mathbb{R}}
\newcommand{\dimens}{\operatorname{dim}}
\DeclareMathOperator{\row}{\operatorname{row}}
\DeclareMathOperator{\col}{\operatorname{col}}
\newcommand{\im}{\operatorname{im}}
\newcommand{\nulls}{\operatorname{null}}
\newcommand{\minor}{\operatorname{minor}}
\newcommand{\spans}{\operatorname{span}}
\newcommand{\nullity}{\operatorname{nullity}}
\newcommand{\kers}{\operatorname{ker}}
\newcommand{\proj}{\operatorname{proj}}
\newcommand{\diag}{\operatorname{diag}}
\newcommand{\Tr}{\operatorname{Tr}}
\newcommand{\rank}{\operatorname{rank}}
\newcommand{\lt}{<}
\newcommand{\gt}{>}
\newcommand{\amp}{&}
\definecolor{fillinmathshade}{gray}{0.9}
\newcommand{\fillinmath}[1]{\mathchoice{\colorbox{fillinmathshade}{$\displaystyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\textstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptstyle \phantom{\,#1\,}$}}{\colorbox{fillinmathshade}{$\scriptscriptstyle\phantom{\,#1\,}$}}}
\)
Section B.5 Dot Products, Norms, Distances, and Cosine Similarity
This section helps you read short NumPy expressions for dot products, lengths, distances, and direction-based comparisons.
u = np.array([3.0, 4.0])
v = np.array([4.0, 3.0])
dot = u @ v
norm_u = np.linalg.norm(u)
distance = np.linalg.norm(u - v)
cosine = (u @ v) / (np.linalg.norm(u) * np.linalg.norm(v))
Dot product.
Read as. The dot product
\(u\cdot v\text{.}\)
Used for. Alignment or score.
Norm.
Read as. The norm
\(\|u\|\text{.}\)
Row-wise norms.
np.linalg.norm(X, axis=1)
Read as. One norm for each row of
X.
Shape/return. A one-dimensional array with one entry per row.
Used for. Row-wise cosine similarities, such as document-ranking scores.
Euclidean distance.
Read as. The Euclidean distance between
\(u\) and
\(v\text{.}\)
Used for. Distance between vectors.
Cosine similarity.
Read as. The cosine similarity
\(\frac{u\cdot v}{\|u\|\|v\|}\text{.}\)
Used for. Direction-based comparison.