Embedding.lean

Lean 4 source, lean/DataMiningAsObservation/Embedding.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.

/-
Embedding.lean. Chapter 11 section 11.1 and chapter 12 section 12.1, the embedding.

An embedding assigns a vector to each object so that nearness in the vector space stands
for a relation between the objects. Two objects with the same embedding are
indistinguishable to every consumer of the embedding, so the embedding is a quotient of
the objects. A cosine reader of the embedding ignores each vector's length, so it takes a
further quotient, and the nearest neighbour under it is unchanged when the query is
rescaled. The encoder that produces the embedding is validated by the gate of chapter 12,
and what the embedding is worth to a consumer is the consumer's number, not the
reconstruction's.
-/
import Mathlib
import DataMiningAsObservation.DotProduct

namespace DMO.Embedding

open Finset DMO.DotProduct

variable {α : Type*} {n : ℕ}

/-- **The embedding is a quotient.** Objects with the same embedding are indistinguishable
to every consumer of the embedding. -/
theorem quotient (emb : α → Fin n → ℝ) (consumer : (Fin n → ℝ) → ℝ) (x y : α)
    (h : emb x = emb y) : consumer (emb x) = consumer (emb y) := by
  rw [h]

/-- **The cosine reader takes a further quotient.** Rescaling an object's embedding by a
positive factor changes no cosine with any other. -/
theorem cosine_scale_free (emb : α → Fin n → ℝ) (x y : α) (c : ℝ) (hc : 0 < c) :
    cosine (c • emb x) (emb y) = cosine (emb x) (emb y) :=
  cosine_smul (emb x) (emb y) c hc

/-- **The cosine nearest neighbour is unchanged when the query is rescaled.** -/
theorem nearest_scale_free (emb : α → Fin n → ℝ) (S : Finset α) (q : Fin n → ℝ) (c : ℝ)
    (hc : 0 < c) (best : α) (hbest : ∀ y ∈ S, cosine q (emb y) ≤ cosine q (emb best)) :
    ∀ y ∈ S, cosine (c • q) (emb y) ≤ cosine (c • q) (emb best) := by
  intro y hy
  rw [cosine_smul q (emb y) c hc, cosine_smul q (emb best) c hc]
  exact hbest y hy

/-- **A dot-product reader does not take that quotient.** Rescaling an object's embedding
scales its dot product with every query. -/
theorem dot_not_scale_free (emb : α → Fin n → ℝ) (x : α) (q : Fin n → ℝ) (c : ℝ) :
    (c • emb x) ⬝ᵥ q = c * (emb x ⬝ᵥ q) :=
  dot_smul (emb x) q c

end DMO.Embedding