@@ -47,59 +47,66 @@ function apply(transform::EigenAnalysis, table)
47
47
# original columns names
48
48
names = Tables. columnnames (table)
49
49
50
- # projection
51
- proj = transform. proj
52
-
50
+ # table as matrix
53
51
X = Tables. matrix (table)
52
+
53
+ # center the data
54
54
μ = mean (X, dims= 1 )
55
- X = X .- μ
56
- Σ = cov (X)
57
- λ, V = eigen (Σ)
58
- S, S⁻¹ = matrices (proj, λ, V)
59
- Y = X * S
55
+ Y = X .- μ
56
+
57
+ # eigenanalysis of covariance
58
+ S, S⁻¹ = eigenmatrices (transform, Y)
59
+
60
+ # project the data
61
+ Z = Y * S
60
62
61
63
# table with transformed columns
62
- 𝒯 = (; zip (names, eachcol (Y ))... )
64
+ 𝒯 = (; zip (names, eachcol (Z ))... )
63
65
newtable = 𝒯 |> Tables. materializer (table)
64
66
65
- newtable, (S⁻¹, μ )
67
+ newtable, (μ, S⁻¹)
66
68
end
67
69
68
70
function revert (:: EigenAnalysis , newtable, cache)
69
71
# transformed column names
70
72
names = Tables. columnnames (newtable)
71
73
72
- Y = Tables. matrix (newtable)
73
- Γ⁻¹, μ = cache
74
- X = Y * Γ⁻¹
75
- X = X .+ μ
74
+ # table as matrix
75
+ Z = Tables. matrix (newtable)
76
+
77
+ # retrieve cache
78
+ μ, S⁻¹ = cache
79
+
80
+ # undo projection
81
+ Y = Z * S⁻¹
82
+
83
+ # undo centering
84
+ X = Y .+ μ
76
85
77
86
# table with original columns
78
87
𝒯 = (; zip (names, eachcol (X))... )
79
88
𝒯 |> Tables. materializer (newtable)
80
89
end
81
90
82
- function matrices (proj, λ, V)
83
- proj == :V && return pcaproj (λ, V)
84
- proj == :VD && return drsproj (λ, V)
85
- proj == :VDV && return sdsproj (λ, V)
86
- end
91
+ function eigenmatrices (transform, Y)
92
+ proj = transform. proj
87
93
88
- function pcaproj (λ, V)
89
- V, transpose (V)
90
- end
94
+ Σ = cov (Y)
95
+ λ, V = eigen (Σ)
91
96
92
- function drsproj (λ, V)
93
- Λ = Diagonal (sqrt .(λ))
94
- S = V * inv (Λ)
95
- S⁻¹ = Λ * transpose (V)
96
- S, S⁻¹
97
- end
97
+ if proj == :V
98
+ S = V
99
+ S⁻¹ = transpose (V)
100
+ elseif proj == :VD
101
+ Λ = Diagonal (sqrt .(λ))
102
+ S = V * inv (Λ)
103
+ S⁻¹ = Λ * transpose (V)
104
+ elseif proj == :VDV
105
+ Λ = Diagonal (sqrt .(λ))
106
+ S = V * inv (Λ) * transpose (V)
107
+ S⁻¹ = V * Λ * transpose (V)
108
+ end
98
109
99
- function sdsproj (λ, V)
100
- Λ = Diagonal (sqrt .(λ))
101
- S = V * inv (Λ) * transpose (V)
102
- S⁻¹ = V * Λ * transpose (V)
103
110
S, S⁻¹
104
111
end
105
112
0 commit comments