SPB Git

Repository Public

LogisticRegressionTool.swift 6.7 KB 85 lines swift

1import Foundation2import SheetCore3import Statistics4import AnalysisKit56/// Binary logistic regression (maximum likelihood by IRLS).7enum LogisticRegressionTool {8    static let descriptor: ToolDescriptor = {9        var t = ToolDescriptor(10            id: "regression.logistic", title: L("Logistic Regression"), group: L("Regression"), systemImage: "point.topleft.down.curvedto.point.bottomright.up",11            summary: L("Models a 0/1 outcome: coefficients, odds ratios, likelihood-ratio test and classification table."),12            fields: [13                .range("data", L("Data range")),14                .column("y", L("Dependent variable (0 / 1)")),15                .columns("x", L("Regressors (X)")),16                .columns("cat", L("Categorical regressors"), numeric: false, all: false),17                .toggle("intercept", L("Include an intercept"), true),18                .number("threshold", L("Classification threshold"), 0.5, min: 0.01, max: 0.99, help: L("A fitted probability at or above the threshold is classified as 1.")),19                .percent("level", L("Confidence level"), 0.95, min: 0.5, max: 0.9999),20                .alpha(L("Significance level α")),21            ],22            info: [23                L("Estimates follow statsmodels Logit (validated to 1e-9); p-values are two-sided normal (Wald) tests."),24                L("Pseudo-R² is McFadden's: 1 − lnL / lnL of the intercept-only model."),25                L("Complete or quasi-complete separation has no finite maximum-likelihood estimate and is reported as “did not converge”."),26            ],27            run: run)28        t.demo = { _, v in v.set("data", range: "Regression!A1:G121"); v.set("y", column: 6); v.set("x", columns: [1, 2]) }29        return t30    }()3132    static func fit(_ input: ToolInput) throws -> (result: LogisticResult, design: RegressionDesign) {33        let d = try RegressionDesign.build(input)34        guard d.y.allSatisfy({ $0 == 0 || $0 == 1 }) else { throw ToolError(L("The dependent variable “%@” must contain only 0 and 1.", d.yName)) }35        guard d.y.contains(0), d.y.contains(1) else { throw ToolError(L("The dependent variable “%@” takes a single value in the rows used.", d.yName)) }36        let r = try LogisticRegression.fit(y: d.y, x: d.x, names: d.names, intercept: input.values.bool("intercept"), threshold: input.values.number("threshold"),37                                           confidenceLevel: Sup.level(input), dependentName: d.yName)38        return (r, d)39    }4041    static func run(_ input: ToolInput) throws -> ToolResult {42        let (r, d) = try fit(input)43        let alpha = Sup.alpha(input), loc = input.locale44        var blocks: [ResultBlock] = [.metrics([45            Metric(L("Observations"), Double(r.nobs), .integer), Metric(L("McFadden pseudo-R²"), r.pseudoRSquared, .fixed(4)),46            Metric(L("LR statistic (χ²)"), r.lrStatistic, .fixed(3)), Metric(L("p-value (LR)"), r.lrPValue ?? .nan, .pValue),47            Metric(L("Accuracy"), r.accuracy, .percent(1)),48        ])]49        blocks.append(.table(Sup.coefficientTable(title: L("Coefficients (log-odds)"), names: r.names, estimates: r.coefficients, se: r.standardErrors, statistics: r.statistics,50                                                  pValues: r.pValues, lower: r.ciLower, upper: r.ciUpper, usesT: false, level: r.confidenceLevel, locale: loc)))51        let pct = Fmt.percent(r.confidenceLevel, 0, locale: loc)52        var odds: [[Value]] = [[.text(L("Term")), .text(L("Odds ratio")), .text(L("%@ CI lower", pct)), .text(L("%@ CI upper", pct))]]53        for i in r.names.indices where r.names[i] != "const" {54            odds.append([.text(r.names[i]), .finite(r.oddsRatios[i]), .finite(exp(r.ciLower[i])), .finite(exp(r.ciUpper[i]))])55        }56        blocks.append(.table(ReportTable(title: L("Odds ratios"), rows: odds, columnFormats: [1: .fixed(4), 2: .fixed(4), 3: .fixed(4)],57                                         note: L("Odds ratio = exp(coefficient): multiplicative change of the odds for a one-unit increase of the regressor."))))58        blocks.append(.table(ReportTable.keyValue(title: L("Fit statistics"), header: (L("Quantity"), L("Value")), [59            (L("Observations"), .finite(Double(r.nobs)), .integer), (L("Log-likelihood"), .finite(r.logLikelihood), .fixed(4)),60            (L("Log-likelihood (intercept only)"), .finite(r.nullLogLikelihood), .fixed(4)), (L("McFadden pseudo-R²"), .finite(r.pseudoRSquared), .fixed(6)),61            (L("LR statistic (χ²)"), .finite(r.lrStatistic), .fixed(4)), (L("Degrees of freedom"), .finite(Double(r.dfModel)), .integer),62            (L("p-value (LR)"), .finite(r.lrPValue), .pValue), ("AIC", .finite(r.aic), .fixed(4)), ("BIC", .finite(r.bic), .fixed(4)),63            (L("Iterations"), .finite(Double(r.iterations)), .integer),64        ])))65        if let p = r.lrPValue { blocks.append(.interpretation(Interpret.decision(p: p, alpha: alpha, null: L("all slope coefficients are zero"), locale: loc))) }66        let c = r.classificationTable67        var ct = ReportTable(title: L("Classification table (threshold %@)", Fmt.fixed(r.threshold, 2, locale: loc)), rows: [68            [.blank, .text(L("Predicted 0")), .text(L("Predicted 1")), .text(L("Correct"))],69            [.text(L("Observed 0")), .number(Double(c[0][0])), .number(Double(c[0][1])), .finite(r.specificity)],70            [.text(L("Observed 1")), .number(Double(c[1][0])), .number(Double(c[1][1])), .finite(r.sensitivity)],71            [.text(L("Overall")), .blank, .blank, .finite(r.accuracy)],72        ], columnFormats: [1: .integer, 2: .integer, 3: .percent(1)])73        ct.note = L("Sensitivity %@, specificity %@.", Fmt.percent(r.sensitivity, 1, locale: loc), Fmt.percent(r.specificity, 1, locale: loc))74        blocks.append(.table(ct))75        blocks.append(.chart(ChartBlock(title: L("Fitted probabilities"), spec: ChartKit.histogram(r.fittedProbabilities, xTitle: L("Fitted probability of 1"), yTitle: L("Frequency")),76                                        summary: L("Histogram of %d fitted probabilities between %@ and %@.", r.nobs,77                                                   Fmt.fixed(r.fittedProbabilities.min() ?? .nan, 3, locale: loc), Fmt.fixed(r.fittedProbabilities.max() ?? .nan, 3, locale: loc)), height: 200)))78        blocks.append(.note(d.notes))79        let actions = [Sup.writeColumns(id: "write-probabilities", title: L("Write Fitted Probabilities"), label: L("Write Fitted Probabilities"), frame: d.frame,80                                        names: [L("P(%@ = 1)", d.yName)], columns: [d.frame.expand(r.fittedProbabilities, rows: d.rows)])]81        return ToolResult(title: L("Logistic Regression"), subtitle: L("%@ — dependent variable: %@", d.frame.label, d.yName),82                          blocks: blocks, actions: actions, sheetName: L("Logistic regression"))83    }84}85
Files main
Menu

Theme