LS fitting

This example illustrates least squares (LS) polynomial fitting using the Julia language.

This page comes from a single Julia file: ls-fit1.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-fit1.ipynb, or open it in binder here: ls-fit1.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: Diagonal, svd
using MIRTjim: prompt
using Plots: default, plot, plot!, scatter, scatter!, savefig
using Random: seed!
default(); default(label="", markerstrokecolor=:auto, widen=true, linewidth=2,
    markersize = 6, tickfontsize=12, labelfontsize = 16, legendfontsize=14)

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);

Simulated data from latent nonlinear function

s = (t) -> atan(4*(t-0.5)) # nonlinear function

seed!(0) # seed rng
M = 15 # how many data points
tm = sort(rand(M)) # M random sample locations
y = s.(tm) + 0.1 * randn(M) # noisy samples

t0 = range(0, 1, 101) # fine sampling for showing curve
xaxis=(L"t", (0,1), 0:0.5:1)
yaxis=(L"y", (-1.3, 1.3), -1:1)
p0 = scatter(tm, y, color=:black, label="y (noisy data)"; xaxis, yaxis)
plot!(t0, s.(t0), color=:blue, label="s(t) : latent signal", legend=:topleft)
Example block output
prompt()

Polynomial fitting

deg = 3 # polynomial degree
Afun = (tt) -> [t.^i for t in tt, i in 0:deg] # matrix of monomials
A = Afun(tm) # M × 4 matrix
p1 = plot(title="Columns of matrix A", xlabel=L"t", legend=:left)
for i in 0:deg
    plot!(p1, tm, A[:,i+1], marker=:circle, label = "A[:,$(i+1)]")
end
p1
Example block output
prompt()

Fit 4 unknowns with 4 equations

m4 = Int64.(round.(range(1, M-1, 4))) # pick 4 points well separated
A4 = A[m4,:] # 4 × 4 matrix
x4 = inv(A4) * y[m4] # inverse of 4×4 matrix to solve "y = A x"

p1 = scatter(tm[m4], y[m4], marker=:square, color=:red)
scatter!(tm, y, color=:black, label="y (noisy data)"; xaxis, yaxis)
plot!(t0, s.(t0), color=:blue, label="s(t) : latent signal", legend=:topleft)
plot!(t0, Afun(t0)*x4, color=:red, label="Fit 4 of $M points")
Example block output
prompt()

Fit 4 unknowns using all M=15 equations

xh = A \ y # backslash for LS solution using all M samples

plot!(p1, t0, Afun(t0)*xh, color=:orange, label="Fit cubic to M=$(M) points")
Example block output
prompt()

# savefig(p1, "ls-fit-4-15.pdf")

SVD solution

U, s, V = svd(A)
s
4-element Vector{Float64}:
 4.942932318799084
 1.6628939736370472
 0.3373293878037186
 0.037596832459397996

Verify equivalence of SVD and backslash solutions to LS problem

xh2 = V * Diagonal(1 ./ s) * (U' * y) # SVD-based solution
xh3 = V * ( (1 ./ s) .* (U' * y) ) # mathematically equivalent alternate expression

@assert xh ≈ xh2
@assert xh ≈ xh3

Reproducibility

This page was generated with the following version of Julia:

using InteractiveUtils: versioninfo
io = IOBuffer(); versioninfo(io); split(String(take!(io)), '\n')
12-element Vector{SubString{String}}:
 "Julia Version 1.10.1"
 "Commit 7790d6f0641 (2024-02-13 20:41 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"
 "  LIBM: libopenlibm"
 "  LLVM: libLLVM-15.0.7 (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.24.0
  [3da002f7] ColorTypes v0.11.4
⌅ [c3611d14] ColorVectorSpace v0.9.10
  [717857b8] DSP v0.7.9
  [72c85766] Demos v0.1.0 `~/work/book-la-demo/book-la-demo`
  [e30172f5] Documenter v1.2.1
  [4f61f5a4] FFTViews v0.3.2
  [7a1cc6ca] FFTW v1.8.0
  [587475ba] Flux v0.14.12
⌅ [a09fc81d] ImageCore v0.9.4
  [71a99df6] ImagePhantoms v0.7.2
  [b964fa9f] LaTeXStrings v1.3.1
  [7031d0ef] LazyGrids v0.5.0
  [599c1a8e] LinearMapsAA v0.11.0
  [98b081ad] Literate v2.16.1
  [7035ae7a] MIRT v0.17.0
  [170b2178] MIRTjim v0.23.0
  [eb30cadb] MLDatasets v0.7.14
  [efe261a4] NFFT v0.13.3
  [6ef6ca0d] NMF v1.0.2
  [15e1cf62] NPZ v0.4.3
  [0b1bfda6] OneHotArrays v0.2.5
  [429524aa] Optim v1.9.2
  [91a5bcdd] Plots v1.40.1
  [f27b6e38] Polynomials v4.0.6
  [2913bbd2] StatsBase v0.34.2
  [d6d074c3] VideoIO v1.0.9
  [b77e0a4c] InteractiveUtils
  [37e2e46d] LinearAlgebra
  [44cfe95a] Pkg v1.10.0
  [9a3f8284] Random
Info Packages marked with ⌅ have new versions available but compatibility constraints restrict them from upgrading. To see why use `status --outdated`

This page was generated using Literate.jl.