Skip to content

Commit

Permalink
Additional show info for PCA (#90)
Browse files Browse the repository at this point in the history
* Additional `show` info for PCA

Co-authored-by: Zachary Christensen <[email protected]>
Co-authored-by: Milan Bouchet-Valat <[email protected]>
Co-authored-by: Art <[email protected]>
  • Loading branch information
4 people authored Mar 3, 2022
1 parent cc5f47d commit 48b2b50
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/MultivariateStats.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ module MultivariateStats
import Statistics: mean, var, cov, covm, cor
import Base: length, size, show, dump
import StatsBase: fit, predict, predict!, ConvergenceException, coef, weights,
dof, pairwise, r2
dof, pairwise, r2, CoefTable
import SparseArrays
import LinearAlgebra: eigvals, eigvecs

Expand Down
26 changes: 25 additions & 1 deletion src/pca.jl
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,36 @@ gives the principal components for an observation, and \$\\mathbf{P}\$ is the pr
reconstruct(M::PCA, y::AbstractVecOrMat{T}) where {T<:Real} = decentralize(M.proj * y, M.mean)

## show & dump

function show(io::IO, M::PCA)
idim, odim = size(M)
print(io, "PCA(indim = $idim, outdim = $odim, principalratio = $(r2(M)))")
end

function show(io::IO, ::MIME"text/plain", M::PCA)
idim, odim = size(M)
print(io, "PCA(indim = $idim, outdim = $odim, principalratio = $(r2(M)))")
ldgs = loadings(M)
rot = diag(ldgs' * ldgs)
ldgs = ldgs[:, sortperm(rot, rev=true)]
ldgs_signs = sign.(sum(ldgs, dims=1))
replace!(ldgs_signs, 0=>1)
ldgs = ldgs * diagm(0 => ldgs_signs[:])
print(io, "\n\nPattern matrix (unstandardized loadings):\n")
cft = CoefTable(ldgs, string.("PC", 1:odim), string.("", 1:idim))
print(io, cft)
print(io, "\n\n")
print(io, "Importance of components:\n")
λ = eigvals(M)
prp = λ ./ var(M)
prpv = λ ./ sum(λ)
names = ["SS Loadings (Eigenvalues)",
"Variance explained", "Cumulative variance",
"Proportion explained", "Cumulative proportion"]
cft = CoefTable(vcat', prp', cumsum(prp)', prpv', cumsum(prpv)'),
string.("PC", 1:odim), names)
print(io, cft)
end

#### PCA Training

## auxiliary
Expand Down

0 comments on commit 48b2b50

Please sign in to comment.