Skip to content

LogisticRegression coefficient norm is 2x sklearn's at identical accuracy, suggesting the penalty is not being applied equivalently #408

Closed

Description

@godofecht

Surfaced by the model-state diagnostics added in PR #402, which took coverage from 3/19 to 19/19.

The observation

On iris, at identical accuracy:

Flow sklearn
coef_frobenius_norm 9.16 4.52

Two models scoring the same while one carries twice the coefficient magnitude of the other are not doing the same thing. This is exactly the class of difference #202 exists to surface, and it was invisible until the diagnostics landed.

Why it is worth chasing

The most likely explanation is that the penalty is not equivalent. sklearn's LogisticRegression applies L2 with C=1.0 by default, where C is the inverse of the regularization strength. flow-scikit's logistic_regression_fit takes penalty as a required argument and uses alpha directly (see lib/scikit/linear.flow:443 and the penalty_l2 constructor).

If the canonical benchmark constructs the Flow model with an alpha that does not correspond to sklearn's C=1.0, or with penalty_none(), then the two rows are comparing a regularized fit against an unregularized one and calling it parity. A larger coefficient norm is what weaker-or-absent regularization looks like.

Candidate explanations, in rough order of likelihood:

  1. The benchmark passes an alpha that is not 1/C for sklearn's default, or passes penalty_none().
  2. The penalty is applied to the gradient but not scaled the same way per sample. Note linear.flow:499-500 computes l2_coeff = penalty.alpha * (1.0 - penalty.l1_ratio) while the LinearRegression path at :355 multiplies by (m as f64). Worth checking whether the logistic path has the same per-sample scaling.
  3. The intercept is being penalized on one side and not the other. sklearn does not penalize the intercept.
  4. The solvers stop at different points. Flow uses LBFGS with no line search (linear.flow:609); a different stopping point leaves coefficients at a different magnitude even with an identical objective.

Suggested first step

Read what the canonical benchmark actually passes for penalty in benchmarks/bench_flow_v2.flow, and compare against the sklearn construction in benchmarks/bench_sklearn_v2.py. If they disagree, that is the answer and the fix is a benchmark change, not a library change. If they agree, the difference is in how the penalty enters the gradient, and that is a library bug.

Note this interacts with #357 (no Newton solver) and with the design position recorded in #358: flow-scikit requires an explicit penalty precisely so this cannot happen silently. It would be unfortunate if the benchmark then did it silently.

Related diagnostics from the same PR worth reading together: LinearSVC carries the same per-class row norm fields, and the KMeans row shows sklearn ending with a singleton cluster at center norm 46.97 against Flow's largest at 11.84.

Activity

  1. godofecht commented on Aug 19, 2026

    @godofecht
    OwnerAuthor

    Finding: benchmark construction mismatch, and the library is doing the right thing

    Did the cheap check first. The two sides are not constructed equivalently.

    benchmarks/bench_flow_v2.flow:784

    let l2_penalty: Penalty = penalty_l2(0.001)
    

    benchmarks/bench_sklearn_v2.py:355,386

    LogisticRegression(max_iter=1000, C=1.0)
    

    The mapping

    Flow's logistic objective is mean loss plus the penalty. linear.flow scales the
    data gradient by inv_m = 1/m (blas_matvec_trans(..., inv_m, 0.0)), then adds
    l2_coeff * theta[j] for j in 0 to n. So it minimises

    (1/m) * sum_i logloss_i + 0.5 * alpha * ||w||^2
    

    sklearn minimises the sum form, sum_i logloss_i + 0.5 * ||w||^2 / C. Divide that
    by m and the two line up only when

    alpha = 1 / (C * n_train)
    

    For iris, n_train = 120, so sklearn's C=1.0 is alpha = 0.008333. The benchmark
    passes 0.001, which is 8.3x weaker. For digits, n_train = 1437, so C=1.0 is
    alpha = 0.000696, and the benchmark's 0.001 is 1.4x stronger.

    The library is not the bug

    I reimplemented Flow's exact objective in numpy (one-vs-rest, mean logloss, penalty
    on weights only, L-BFGS-B run to a tight tolerance) on the same fixture split and
    scaler:

    alpha iris frobenius iris accuracy
    0.001 (what the benchmark passes) 9.1606 0.933333333
    0.008333 (= 1/(C*m), sklearn-equivalent) 4.9371 0.900000000
    sklearn C=1.0, multinomial 4.5173 0.933333333

    9.1606 against the reported Flow coef_frobenius_norm of 9.16. Flow's LBFGS is
    landing on the true optimum of the objective it was asked to minimise. Checking the
    three library hypotheses in the issue individually:

    1. Per-sample scaling. Both paths use a mean-loss convention. Logistic divides
      the data gradient by m and leaves the penalty unscaled; LinearRegression keeps
      the sum form and multiplies alpha by m at linear.flow:356. Same convention,
      opposite bookkeeping. Not the cause.
    2. Intercept penalization. Flow does not penalize the intercept. The penalty
      loop is for j in 0 to n over the augmented theta of dimension d = n + 1, so
      the bias at index n is excluded. Matches sklearn.
    3. Stopping point. The numpy replica converged to a gradient norm of 1e-10 and
      reproduced Flow's norm to three significant figures, so the no-line-search LBFGS
      is not stopping short here.

    The uncomfortable part

    benchmarks/parity_contract.json already records the mismatch in its own row data:

    "flow":    {"optimizer": "gradient_descent", "max_iter": 200, "learning_rate": 0.1, "l2": 0.001, ...}
    "sklearn": {"optimizer": "lbfgs", "max_iter": 1000, "C": 1.0, ...}
    

    (The gradient_descent label is also stale; the path has been LBFGS since the
    augmented-theta rewrite.)

    Setting alpha = 1/(C*n_train) to make the two objectives equivalent moves the
    canonical rows:

    • iris 0.933333337 -> 0.900000 (replica). Against sklearn's 0.933333 that is a
      gap of 0.0333, which exceeds the row's score_abs_tolerance of 0.02 and fails
      the parity gate.
    • digits 0.972222209 -> 0.969444 (replica). Still inside tolerance.

    So the honest version of this issue is a trade. The current benchmark buys iris
    accuracy parity with a regularization strength that is 8x weaker than the model it
    is being compared against. Matching the penalty makes the coefficient norms
    comparable and makes the iris accuracy row fail.

    A second, separate difference remains even with alpha matched: sklearn 1.9 fits
    multiclass logistic as a single multinomial softmax, while Flow fits one-vs-rest.
    At matched alpha the iris frobenius norms are 4.94 (Flow, OvR) against 4.52
    (sklearn, multinomial), and on digits 15.19 against 10.36. OvR and softmax do not
    have the same optimum, so coef_frobenius_norm will not reach exact parity by
    fixing alpha alone.

    Measuring in Flow itself now, then proposing which way to take it. This bears on
    #358: flow-scikit demands an explicit penalty argument so that regularization
    cannot be applied silently, and the canonical benchmark then picked a value with no
    stated relationship to the model it publishes a comparison against.

  2. godofecht commented on Aug 19, 2026

    @godofecht
    OwnerAuthor

    Measured in Flow, and PR #430 is open

    The canonical benchmark confirms the numpy replica exactly. Full run on
    origin/main against the branch, diffing every RESULT| score and every
    DETAIL| record:

    before after sklearn
    iris accuracy 0.933333337 0.899999976 0.933333333
    iris coef_frobenius_norm 9.161066 4.937423 4.517331
    digits accuracy 0.972222209 0.969444454 0.972222222
    digits coef_frobenius_norm 13.641894 15.171825 10.364157

    Only those eight lines move. All 17 other canonical rows, including everything
    else in linear.flow, are byte-identical, which also clears #469 for this edit.

    Two things to weigh.

    The iris score gap goes from ~0 to 0.0333, above the row's declared
    score_abs_tolerance of 0.02, so the row reclassifies from
    approximately equivalent to not parity verified. I did not touch the
    tolerance or disparity_regression_policy.json. Iris has 30 test samples, so
    0.0333 is one sample: at equal regularization, one-vs-rest gets 27 of 30 where
    sklearn's multinomial gets 28.

    The digits norm gap gets worse, 1.32x to 1.46x. The old flat 0.001 was 1.4x
    stronger than C=1.0 on digits, so it was partly masking the second
    difference: sklearn 1.9 fits one multinomial softmax while
    logistic_regression_fit fits one-vs-rest. Fixing alpha is what makes that
    visible on its own. MultiClassLogisticRegression in the same file already does
    softmax, on plain gradient descent, so moving the canonical row onto it is not a
    small change and is not in this PR.

    PR #430 also adds penalty_l2_from_c(C, n_samples) so the conversion is written
    down rather than inferred, corrects the contract's stale gradient_descent
    optimizer label, and records the mapping in the design rationale.

  3. added a commit that references this issue on Aug 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions