LS cost functions

This example illustrates linear least-squares (LS) cost functions and minimum-norm LS (MNLS) solutions using the Julia language.

This page comes from a single Julia file: ls-cost1.jl.

You can access the source code for such Julia documentation using the 'Edit on GitHub' link in the top right. You can view the corresponding notebook in nbviewer here: ls-cost1.ipynb, or open it in binder here: ls-cost1.ipynb.

Setup

Add the Julia packages used in this demo. Change false to true in the following code block if you are using any of the following packages for the first time.

if false
    import Pkg
    Pkg.add([
        "InteractiveUtils"
        "LaTeXStrings"
        "LinearAlgebra"
        "MIRTjim"
        "Plots"
        "Random"
    ])
end

Tell Julia to use the following packages. Run Pkg.add() in the preceding code block first, if needed.

using InteractiveUtils: versioninfo
using LaTeXStrings
using LinearAlgebra: norm, pinv
using MIRTjim: prompt
using Plots: default, contour, plot!, scatter!, savefig
using Random: seed!
default(); default(label="", markerstrokecolor=:auto, markersize=6, linewidth=2,
    xlims = (-3,3), ylims = (-3,3), aspect_ratio=:equal, size=(450,400),
    legendfontsize=12, guidefontsize=13, tickfontsize=10, labelfontsize=18)

The following line is helpful when running this jl-file as a script; this way it will prompt user to hit a key after each image is displayed.

isinteractive() && prompt(:prompt);

Under-determined case

A = [1 2] # 1st case: M < N
y = [3] # obviously x=[1 1] is one possible solution (but not MNLS)
f1(x) = norm(A*x - y)
xh1 = A \ y

x1 = range(-1,1,101) * 3
x2 = range(-1,1,103) * 3
c1 = [f1([x1a, x2a]) for x1a in x1, x2a in x2];

flabel(n) = L"\{%$bx : y_{%$n} = %$(bA)_{[%$n,:]} %$bx\}"
bx = "\\mathit{\\mathbf{x}}"
by = "\\mathit{\\mathbf{y}}"
bA = "\\mathit{\\mathbf{A}}"
color = :viridis
p1 = contour(x1, x2, c1', label="contours"; color)
plot!(xlabel=L"x_1", ylabel=L"x_2", legend=:bottomleft)
scatter!([0], [0], color=:black, markershape=:square)
plot!([0, xh1[1]], [0, xh1[2]], line=:magenta)
plot!(x1, (y[1] .- A[1,1]*x1)/A[1,2], line=(:blue,:dash),
    label=L"\{%$bx : %$by = %$bA %$bx\}")
scatter!([1], [1], color=:blue, markershape=:star5, label=L"(1,1)")
scatter!([xh1[1]], [xh1[2]], color=:red, markershape=:circle, label="MNLS",
    title = "Under-determined case")
Example block output
prompt()

# savefig(p1, "demo_ls_cost1a.pdf")

Square but singular case

A = [1 2; 2 4] # 2nd case: M = N but singular A
y = [3, 6] # again [1,1] is a solution (but not MNLS solution)
f2(x) = norm(A*x - y)
xh2 = pinv(A) * y

c2 = [f2([x1a, x2a]) for x1a in x1, x2a in x2]
p2 = contour(x1, x2, c2', label="contours"; color)
plot!(xlabel=L"x_1", ylabel=L"x_2", legend=:bottomleft)
scatter!([0], [0], color=:black, markershape=:square)
plot!([0, xh2[1]], [0, xh2[2]], line=:magenta)
plot!(x1, (y[1] .- A[1,1]*x1)/A[1,2], line=(:blue,:dash), label=flabel(1))
plot!(x1, (y[2] .- A[2,1]*x1)/A[2,2], line=(:green,:dashdot), label=flabel(2))
scatter!([1], [1], color=:blue, markershape=:star5, label=L"(1,1)")
scatter!([xh2[1]], [xh2[2]], color=:red, markershape=:circle, label="MNLS",
 title = "Singular case")
Example block output
prompt()

# savefig(p2, "demo_ls_cost1b.pdf")

Square non-singular case

A = [1 2; 1 3] # 3rd case: M = N with non-singular A
y = [3, 4] # now x=[1,1] is the unique solution (by design)
f3(x) = norm(A*x - y)
xh3 = A \ y

c3 = [f3([x1a, x2a]) for x1a in x1, x2a in x2]
p3 = contour(x1, x2, c3', label="contours"; color)
plot!(xlabel=L"x_1", ylabel=L"x_2", legend=:bottomleft)
plot!(x1, (y[1] .- A[1,1]*x1)/A[1,2], line=(:blue,:dash), label=flabel(1))
plot!(x1, (y[2] .- A[2,1]*x1)/A[2,2], line=(:green,:dash), label=flabel(2))
scatter!([xh3[1]], [xh3[2]], color=:red, markershape=:circle, label="LLS",
 title = "Non-singular case")
Example block output
prompt()

# savefig(p3, "demo_ls_cost1c.pdf")

Typical over-determined case

A = [1 2; 1 -1; 2 1] # 4th case: M > N with (typical) inconsistent data
y = [3, 2, 1] # no consistent solution
f4(x) = norm(A*x - y)
xh4 = A \ y

c4 = [f4([x1a, x2a]) for x1a in x1, x2a in x2]
p4 = contour(x1, x2, c4', label="contours"; color)
plot!(xlabel=L"x_1", ylabel=L"x_2", legend=:bottomleft)
plot!(x1, (y[1] .- A[1,1]*x1)/A[1,2], line=(:blue,:dash), label=flabel(1))
plot!(x1, (y[2] .- A[2,1]*x1)/A[2,2], line=(:green,:dash), label=flabel(2))
plot!(x1, (y[3] .- A[3,1]*x1)/A[3,2], line=(:purple,:dash), label=flabel(3))
scatter!([xh4[1]], [xh4[2]], color=:red, markershape=:circle, label="LLS",
    title = "Over-determined case")
Example block output
prompt()

# savefig(p4, "demo_ls_cost1d.pdf")

Reproducibility

This page was generated with the following version of Julia:

using InteractiveUtils: versioninfo
io = IOBuffer(); versioninfo(io); split(String(take!(io)), '\n')
11-element Vector{SubString{String}}:
 "Julia Version 1.11.1"
 "Commit 8f5b7ca12ad (2024-10-16 10:53 UTC)"
 "Build Info:"
 "  Official https://julialang.org/ release"
 "Platform Info:"
 "  OS: Linux (x86_64-linux-gnu)"
 "  CPU: 4 × AMD EPYC 7763 64-Core Processor"
 "  WORD_SIZE: 64"
 "  LLVM: libLLVM-16.0.6 (ORCJIT, znver3)"
 "Threads: 1 default, 0 interactive, 1 GC (on 4 virtual cores)"
 ""

And with the following package versions

import Pkg; Pkg.status()
Status `~/work/book-la-demo/book-la-demo/docs/Project.toml`
  [6e4b80f9] BenchmarkTools v1.5.0
  [aaaa29a8] Clustering v0.15.7
  [35d6a980] ColorSchemes v3.27.1
⌅ [3da002f7] ColorTypes v0.11.5
⌃ [c3611d14] ColorVectorSpace v0.10.0
  [717857b8] DSP v0.7.10
  [72c85766] Demos v0.1.0 `~/work/book-la-demo/book-la-demo`
  [e30172f5] Documenter v1.7.0
  [4f61f5a4] FFTViews v0.3.2
  [7a1cc6ca] FFTW v1.8.0
  [587475ba] Flux v0.14.25
  [a09fc81d] ImageCore v0.10.4
  [71a99df6] ImagePhantoms v0.8.1
  [b964fa9f] LaTeXStrings v1.4.0
  [7031d0ef] LazyGrids v1.0.0
  [599c1a8e] LinearMapsAA v0.12.0
  [98b081ad] Literate v2.20.1
  [7035ae7a] MIRT v0.18.2
  [170b2178] MIRTjim v0.25.0
  [eb30cadb] MLDatasets v0.7.18
  [efe261a4] NFFT v0.13.5
  [6ef6ca0d] NMF v1.0.3
  [15e1cf62] NPZ v0.4.3
  [0b1bfda6] OneHotArrays v0.2.5
  [429524aa] Optim v1.10.0
  [91a5bcdd] Plots v1.40.9
  [f27b6e38] Polynomials v4.0.11
  [2913bbd2] StatsBase v0.34.3
  [d6d074c3] VideoIO v1.1.0
  [b77e0a4c] InteractiveUtils v1.11.0
  [37e2e46d] LinearAlgebra v1.11.0
  [44cfe95a] Pkg v1.11.0
  [9a3f8284] Random v1.11.0
Info Packages marked with ⌃ and ⌅ have new versions available. Those with ⌃ may be upgradable, but those with ⌅ are restricted by compatibility constraints from upgrading. To see why use `status --outdated`

This page was generated using Literate.jl.