SPB Git

Repository Public

RegressionOutput.swift 5.4 KB 75 lines swift

1import Foundation2import SheetCore3import Statistics4import AnalysisKit56/// Diagnostics table and residual plots of a linear model.7enum RegressionOutput {8    struct Diagnostics {9        var table: ReportTable10        /// Null hypothesis of each test, localized.11        var nulls: [String]12        /// Tests that could not be computed.13        var notes: [String]14    }1516    static func diagnostics(_ m: LinearModelResult, lags: Int, alpha: Double, locale: Locale) -> Diagnostics {17        var rows: [[Value]] = [[.text(L("Test")), .text(L("Statistic")), .text(L("Reference distribution")), .text(L("p-value")), .text(Sup.decisionHeader(alpha, locale))]]18        var nulls = [String](), notes = [String]()19        func add(_ name: String, null: String?, _ body: () throws -> RegressionDiagnostic) {20            do {21                let d = try body()22                rows.append([.text(name), .finite(d.statistic), .text(d.distribution.replacingOccurrences(of: "chi2", with: "χ²")), .finite(d.pValue), Sup.decision(d.pValue, alpha)])23            } catch {24                rows.append([.text(name), .text("—"), .blank, .blank, .blank])25                notes.append(L("%@ could not be computed: %@", name, ToolError.describe(error)))26            }27            if let null { nulls.append(name + " — " + null) }28        }29        let k = max(1, min(lags, max(1, m.nobs - m.names.count - 2)))30        add(L("Breusch–Pagan (studentized)"), null: L("the error variance is constant (homoskedasticity)")) { try RegressionDiagnostics.breuschPagan(m) }31        add(L("White"), null: L("the error variance is constant (homoskedasticity)")) { try RegressionDiagnostics.white(m) }32        add(L("Durbin–Watson"), null: nil) { RegressionDiagnostics.durbinWatson(m) }33        add(L("Breusch–Godfrey (%d lags)", k), null: L("no serial correlation of the errors up to the chosen lag")) { try RegressionDiagnostics.breuschGodfrey(m, lags: k) }34        add(L("Ljung–Box on residuals (%d lags)", k), null: L("the residuals are not autocorrelated up to the chosen lag")) { try RegressionDiagnostics.ljungBox(m.residuals, lags: k) }35        add(L("Jarque–Bera on residuals"), null: L("the errors are normally distributed (skewness 0, excess kurtosis 0)")) { try RegressionDiagnostics.jarqueBera(m) }36        add(L("Ramsey RESET (powers 2–3)"), null: L("the linear functional form is adequate")) { try RegressionDiagnostics.reset(m) }37        var table = ReportTable(title: L("Diagnostics"), rows: rows, columnFormats: [1: .fixed(4), 3: .pValue])38        table.note = L("Durbin–Watson has no p-value: values near 2 indicate no first-order autocorrelation.")39        return Diagnostics(table: table, nulls: nulls, notes: notes)40    }4142    static func vifTable(_ m: LinearModelResult) -> ReportTable? {43        let pairs = zip(m.names, m.vif).compactMap { n, v in v.map { (n, $0) } }44        guard !pairs.isEmpty else { return nil }45        return ReportTable(title: L("Variance inflation factors"),46                           rows: [[.text(L("Regressor")), .text("VIF")]] + pairs.map { [.text($0.0), .finite($0.1)] },47                           columnFormats: [1: .fixed(3)], note: L("VIF = 1/(1 − R²) of each regressor on the others; values above 10 are a common sign of strong collinearity."))48    }4950    static func residualCharts(_ m: LinearModelResult, locale: Locale) -> [ChartBlock] {51        let e = m.residuals52        let sd = Descriptive.standardDeviation(e)53        let qq = ChartKit.normalQQ(m.studentizedResiduals)54        let maxCook = m.cooksDistance.filter(\.isFinite).max() ?? 055        let worst = m.cooksDistance.firstIndex(of: maxCook).map { $0 + 1 } ?? 056        var qqSpec = ChartKit.scatter([(L("Studentized residuals"), qq.theoretical, qq.ordered)], xTitle: L("Theoretical normal quantile"), yTitle: L("Studentized residual"))57        if let lo = qq.theoretical.first, let hi = qq.theoretical.last {58            qqSpec.annotations.append(.arrow(fromX: lo, y: lo, toX: hi, y: hi))59        }60        return [61            ChartBlock(title: L("Residuals vs fitted values"),62                       spec: ChartKit.scatter([(L("Residuals"), m.fitted, e)], xTitle: L("Fitted value"), yTitle: L("Residual"), horizontal: [0]),63                       summary: L("Scatter of %d residuals against fitted values; residual standard deviation %@.", e.count, Fmt.number(sd, locale: locale)), height: 220),64            ChartBlock(title: L("Normal Q–Q plot of studentized residuals"), spec: qqSpec,65                       summary: L("Ordered studentized residuals against normal quantiles; smallest %@, largest %@.",66                                  Fmt.number(qq.ordered.first ?? .nan, locale: locale), Fmt.number(qq.ordered.last ?? .nan, locale: locale)), height: 220),67            ChartBlock(title: L("Histogram of residuals"), spec: ChartKit.histogram(e, xTitle: L("Residual"), yTitle: L("Frequency")),68                       summary: L("Histogram of %d residuals centred on zero with standard deviation %@.", e.count, Fmt.number(sd, locale: locale)), height: 220),69            ChartBlock(title: L("Leverage and Cook's distance"),70                       spec: ChartKit.scatter([(L("Observations"), m.leverage, m.cooksDistance)], xTitle: L("Leverage"), yTitle: L("Cook's distance")),71                       summary: L("Cook's distance against leverage; the largest Cook's distance is %@ (observation %d).", Fmt.number(maxCook, locale: locale), worst), height: 220),72        ]73    }74}75
Files main
Menu

Theme