Rank-1 approximation

This example illustrates rank-1 approximations using the Julia language.

This page comes from a single Julia file: rank1.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: rank1.ipynb, or open it in binder here: rank1.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: svd, rank
using MIRTjim: prompt
using Plots: default, plot!, scatter, scatter!, savefig
using Random: seed!
default(); default(label="", markerstrokecolor=:auto,
    guidefontsize=14, legendfontsize=14, tickfontsize=12)

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

Generate data

Noisy data with slope=1. Both x and y values are noisy!

seed!(0)
x0 = 1:8 # true x locations
x = x0 + 2*randn(size(x0)) # called "errors in variables"
y = x0 + 2*randn(size(x0)); # noisy samples

Plotting utility function

lineplot = (p, s, c, l; w=3, t=:dash) ->
    plot!(p, 0:10, (0:10)*s, line=(c,t), label=l, width=w)
function plotdata()
    p = scatter(x, y, label="data", legend=:bottomright,
        color=:blue, markersize=7, aspect_ratio=:equal,
        xaxis = (L"x", (0, 10), 0:4:8),
        yaxis = (L"y", (0, 10), 0:4:8),
    )
    lineplot(p, 1, :red, "true", t=:solid, w=2)
end
pl = plotdata()
Example block output
prompt()

Rank-1 approximation

To make a low-rank approximation, collect data into a matrix

A = [x'; y']
2×8 Matrix{Float64}:
 0.536182  3.88078  4.19352  7.99565  4.89688  8.34449  3.60637  3.76771
 1.59638   4.6866   2.95151  5.92748  6.15736  8.9353   3.46714  9.21751

Examine singular values

U, s, V = svd(A)
s # 2nd singular value is much smaller than 1st
2-element Vector{Float64}:
 21.9875414774831
  4.16157385887153

Construct rank-1 approximation

B = U[:,1] * s[1] * V[:,1]' # rank-1 approximation
rank(B)
1
B
2×8 Matrix{Float64}:
 1.02075  3.98817  3.26364  6.37115  5.15302  8.01012  3.26653  6.1826
 1.17565  4.59336  3.75888  7.33794  5.93496  9.22562  3.76221  7.12078

Plot rank-1 approximation

xb = B[1,:]
yb = B[2,:]

lineplot(pl, (xb\yb)[1], :black, "")
scatter!(pl, xb, yb, color=:black, markersize=5, marker=:square, label="rank1")
Example block output
prompt()

Use least-squares estimation to estimate slope:

slope = y'*x / (x'*x) # cf inv(A'A) * A'b
slope = (x \ y)[1] # cf A \ b
1.0601098597829095

Plot the LS fit and the low-rank approximation on same graph

pa = lineplot(pl, slope, :green, "LS")
Example block output
prompt()

# savefig(pa, "06_low_rank1_all.pdf")

Illustrate the Frobenius norm approximation error graphically

pf = plotdata()
for i in 1:length(xb)
    plot!(pf, [x[i], xb[i]], [y[i], yb[i]], color=:black, width=2)
end
lineplot(pf, (xb\yb)[1], :black, "")
scatter!(pf, xb, yb, color=:black, markersize=5, marker=:square, label="rank1")
Example block output
prompt()

# savefig(pf, "06_low_rank1_r1.pdf")

Illustrate the LS residual graphically

xl = x; yl = slope*xl # LS points
ps = plotdata()
for i in 1:length(x)
    plot!(ps, [x[i], xl[i]], [y[i], yl[i]], color=:green, width=2)
end
lineplot(ps, slope, :green, "")
scatter!(ps, xl, yl, color=:green, markersize=5, marker=:square, label="LS")
Example block output
prompt()

# savefig(ps, "06_low_rank1_ls.pdf")

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.