SPB Git

Repository Public

PCA.swift 5.7 KB 112 lines swift

1import Foundation2import SheetCore34/// Principal component analysis result.5public struct PCAResult: Sendable, Hashable, Codable, TableReport {6    public var variableNames: [String]7    /// Number of observations.8    public var n: Int9    /// Column means removed before the decomposition.10    public var means: [Double]11    /// Column scales the centred data were divided by (sample standard deviations for a correlation PCA, 1 otherwise).12    public var scales: [Double]13    /// True when the analysis was run on the correlation matrix.14    public var standardized: Bool15    /// Principal axes (unit eigenvectors), one per ROW, in decreasing order of variance (k × p).16    /// Sign convention: the entry of largest absolute value in each axis is positive.17    public var components: Matrix18    /// Variance of each component = eigenvalue of the covariance (or correlation) matrix, divisor n − 1.19    public var explainedVariance: [Double]20    /// Share of the total variance carried by each component.21    public var explainedVarianceRatio: [Double]22    /// Singular values of the centred (and scaled) data matrix.23    public var singularValues: [Double]24    /// Sum of all p eigenvalues (trace of the analysed matrix; equals p for a correlation PCA).25    public var totalVariance: Double26    /// Component scores of the observations (n × k).27    public var scores: Matrix2829    public var cumulativeVarianceRatio: [Double] {30        var acc = 0.031        return explainedVarianceRatio.map { acc += $0; return acc }32    }3334    /// Loadings (p × k): eigenvector × √eigenvalue. For a correlation PCA these are the correlations35    /// between the variables and the components.36    public var loadings: Matrix {37        var l = Matrix(rows: components.cols, cols: components.rows)38        for c in 0..<components.rows {39            let s = max(explainedVariance[c], 0).squareRoot()40            for v in 0..<components.cols { l[v, c] = components[c, v] * s }41        }42        return l43    }4445    /// Projects new observations (rows) onto the components.46    public func transform(_ data: Matrix) throws -> Matrix {47        guard data.cols == means.count else { throw StatError.invalidInput("data must have \(means.count) columns") }48        var z = data49        for r in 0..<z.rows { for c in 0..<z.cols { z[r, c] = (z[r, c] - means[c]) / scales[c] } }50        return z * components.transposed51    }5253    public func table() -> [[Value]] {54        let k = components.rows55        let names = (1...max(k, 1)).map { "PC\($0)" }56        var out: [[Value]] = [[.text("Principal component analysis (\(standardized ? "correlation" : "covariance") matrix)")]]57        out.append([.text("")] + names.map { .text($0) })58        out.append([.text("Eigenvalue")] + explainedVariance.map { Report.num($0) })59        out.append([.text("Proportion of variance")] + explainedVarianceRatio.map { Report.num($0) })60        out.append([.text("Cumulative proportion")] + cumulativeVarianceRatio.map { Report.num($0) })61        out.append([.text("Loadings (eigenvectors)")])62        for (v, name) in variableNames.enumerated() {63            out.append([.text(name)] + (0..<k).map { Report.num(components[$0, v]) })64        }65        return Report.rectangular(out)66    }67}6869public enum PCA {70    /// Principal component analysis by singular value decomposition of the centred data matrix.71    /// - Parameters:72    ///   - data: observations in rows, variables in columns.73    ///   - standardize: true = scale each variable to unit sample variance (PCA of the correlation matrix);74    ///     false = PCA of the covariance matrix.75    ///   - components: number of components to keep (nil = min(n − 1, p)).76    public static func fit(_ data: Matrix, standardize: Bool = false, components: Int? = nil, names: [String]? = nil) throws -> PCAResult {77        let n = data.rows, p = data.cols78        guard n >= 2, p >= 1 else { throw StatError.insufficientData("PCA needs at least 2 observations and 1 variable") }79        guard data.data.allSatisfy(\.isFinite) else { throw StatError.invalidInput("data contain non-finite values") }80        if let names, names.count != p { throw StatError.invalidInput("one name per variable is required") }81        let maxK = min(n - 1, p)82        let k = components ?? maxK83        guard k >= 1, k <= maxK else { throw StatError.invalidInput("components must be between 1 and \(maxK)") }84        var means = [Double](repeating: 0, count: p), scales = [Double](repeating: 1, count: p)85        for c in 0..<p {86            let col = data.column(c)87            means[c] = Descriptive.mean(col)88            if standardize {89                let sd = Descriptive.standardDeviation(col)90                guard sd > 0 else { throw StatError.invalidInput("variable \(c + 1) is constant: it cannot be standardised") }91                scales[c] = sd92            }93        }94        var z = data95        for r in 0..<n { for c in 0..<p { z[r, c] = (z[r, c] - means[c]) / scales[c] } }96        let (_, s, vt) = try LinearAlgebra.svd(z)97        let eig = s.map { $0 * $0 / Double(n - 1) }98        let total = eig.reduce(0, +)99        var comp = Matrix(rows: k, cols: p)100        for i in 0..<k {101            var big = 0102            for c in 1..<max(p, 1) where abs(vt[i, c]) > abs(vt[i, big]) { big = c }103            let sign: Double = vt[i, big] < 0 ? -1 : 1104            for c in 0..<p { comp[i, c] = sign * vt[i, c] }105        }106        return PCAResult(variableNames: names ?? (1...p).map { "X\($0)" }, n: n, means: means, scales: scales, standardized: standardize,107                         components: comp, explainedVariance: Array(eig.prefix(k)),108                         explainedVarianceRatio: eig.prefix(k).map { total > 0 ? $0 / total : .nan },109                         singularValues: Array(s.prefix(k)), totalVariance: total, scores: z * comp.transposed)110    }111}112
Files main
Menu

Theme