Skip to content

Commit 48b2b50

Browse files
TokazamaZachary Christensennalimilanwildart
authored
Additional show info for PCA (#90)
* Additional `show` info for PCA Co-authored-by: Zachary Christensen <zchristensen@nsc-foxemacpro.urmc-sh.rochester.edu> Co-authored-by: Milan Bouchet-Valat <nalimilan@club.fr> Co-authored-by: Art <wildart@users.noreply.github.com>
1 parent cc5f47d commit 48b2b50

File tree

2 files changed

+26
-2
lines changed

2 files changed

+26
-2
lines changed

src/MultivariateStats.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ module MultivariateStats
55
import Statistics: mean, var, cov, covm, cor
66
import Base: length, size, show, dump
77
import StatsBase: fit, predict, predict!, ConvergenceException, coef, weights,
8-
dof, pairwise, r2
8+
dof, pairwise, r2, CoefTable
99
import SparseArrays
1010
import LinearAlgebra: eigvals, eigvecs
1111

src/pca.jl

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,12 +135,36 @@ gives the principal components for an observation, and \$\\mathbf{P}\$ is the pr
135135
reconstruct(M::PCA, y::AbstractVecOrMat{T}) where {T<:Real} = decentralize(M.proj * y, M.mean)
136136

137137
## show & dump
138-
139138
function show(io::IO, M::PCA)
140139
idim, odim = size(M)
141140
print(io, "PCA(indim = $idim, outdim = $odim, principalratio = $(r2(M)))")
142141
end
143142

143+
function show(io::IO, ::MIME"text/plain", M::PCA)
144+
idim, odim = size(M)
145+
print(io, "PCA(indim = $idim, outdim = $odim, principalratio = $(r2(M)))")
146+
ldgs = loadings(M)
147+
rot = diag(ldgs' * ldgs)
148+
ldgs = ldgs[:, sortperm(rot, rev=true)]
149+
ldgs_signs = sign.(sum(ldgs, dims=1))
150+
replace!(ldgs_signs, 0=>1)
151+
ldgs = ldgs * diagm(0 => ldgs_signs[:])
152+
print(io, "\n\nPattern matrix (unstandardized loadings):\n")
153+
cft = CoefTable(ldgs, string.("PC", 1:odim), string.("", 1:idim))
154+
print(io, cft)
155+
print(io, "\n\n")
156+
print(io, "Importance of components:\n")
157+
λ = eigvals(M)
158+
prp = λ ./ var(M)
159+
prpv = λ ./ sum(λ)
160+
names = ["SS Loadings (Eigenvalues)",
161+
"Variance explained", "Cumulative variance",
162+
"Proportion explained", "Cumulative proportion"]
163+
cft = CoefTable(vcat', prp', cumsum(prp)', prpv', cumsum(prpv)'),
164+
string.("PC", 1:odim), names)
165+
print(io, cft)
166+
end
167+
144168
#### PCA Training
145169

146170
## auxiliary

0 commit comments

Comments
 (0)