SPB Git

Repository Public

Design.swift 3.7 KB 70 lines swift

1import Foundation23/// Result of expanding a categorical variable into 0/1 indicator columns.4public struct DummyEncoding: Codable, Sendable, Hashable {5    /// Column names, `"<prefix>[<level>]"`.6    public var names: [String]7    /// One indicator column per retained level.8    public var columns: [[Double]]9    /// All distinct levels, in the order used for the columns (before dropping the baseline).10    public var levels: [String]11    /// The omitted reference level (nil when no level was dropped).12    public var baseline: String?13}1415public enum Categorical {16    /// Expands category labels into indicator (dummy) columns.17    /// - Parameters:18    ///   - dropFirst: omit the first level (the reference category) so the columns are not collinear19    ///     with an intercept. Use `false` only in models without an intercept.20    ///   - levels: explicit level order; by default levels are sorted (localised-independent, by code unit),21    ///     so the baseline is the smallest label.22    /// - Throws: when a value is not in the explicit `levels`.23    public static func dummies(_ values: [String], prefix: String, dropFirst: Bool = true, levels explicit: [String]? = nil) throws -> DummyEncoding {24        let levels = explicit ?? Array(Set(values)).sorted()25        guard Set(levels).count == levels.count else { throw StatError.invalidInput("duplicate category levels") }26        var index = [String: Int]()27        for (i, l) in levels.enumerated() { index[l] = i }28        var cols = Array(repeating: [Double](repeating: 0, count: values.count), count: levels.count)29        for (r, v) in values.enumerated() {30            guard let i = index[v] else { throw StatError.invalidInput("value '\(v)' is not among the declared levels") }31            cols[i][r] = 132        }33        let start = dropFirst && !levels.isEmpty ? 1 : 034        return DummyEncoding(names: levels[start...].map { "\(prefix)[\($0)]" }, columns: Array(cols[start...]),35                             levels: levels, baseline: start == 1 ? levels[0] : nil)36    }37}3839/// Assembles a regressor matrix from named numeric and categorical variables.40/// The intercept is not part of the builder: `LinearRegression.fit(intercept:)` adds it.41public struct DesignBuilder: Sendable {42    public private(set) var names: [String] = []43    public private(set) var columns: [[Double]] = []44    /// Reference level of each categorical variable, keyed by variable name.45    public private(set) var baselines: [String: String] = [:]46    public init() {}4748    public mutating func addNumeric(_ name: String, _ values: [Double]) {49        names.append(name); columns.append(values)50    }5152    /// Adds drop-first dummies for a categorical variable (see `Categorical.dummies`).53    public mutating func addCategorical(_ name: String, _ values: [String], dropFirst: Bool = true, levels: [String]? = nil) throws {54        let enc = try Categorical.dummies(values, prefix: name, dropFirst: dropFirst, levels: levels)55        names.append(contentsOf: enc.names); columns.append(contentsOf: enc.columns)56        if let b = enc.baseline { baselines[name] = b }57    }5859    /// Adds the product of two existing columns (an interaction term) under the name "a:b".60    public mutating func addInteraction(_ a: String, _ b: String) throws {61        guard let i = names.firstIndex(of: a), let j = names.firstIndex(of: b) else { throw StatError.invalidInput("unknown column in interaction \(a):\(b)") }62        names.append("\(a):\(b)"); columns.append(zip(columns[i], columns[j]).map(*))63    }6465    public func matrix() throws -> Matrix {66        guard let n = columns.first?.count, columns.allSatisfy({ $0.count == n }) else { throw StatError.invalidInput("columns are empty or of unequal length") }67        return Matrix(columns: columns)68    }69}70
Files main
Menu

Theme