Repository navigation
Conversation
4 of 5 tasks
Member
Author
|
Merge order. These open PRs build on this one (their branches contain its commits), so please merge this PR first:
Indented PRs build on the PR above them, so merge them after it. Once this PR is merged, their diffs shrink to their own changes. Each of them also says "Stacked on #..." at the top of its description. Merge-order note generated with Claude Code (updated 2026-11-25). |
bashtage
added a commit
to bashtage/statsmodels
that referenced
this pull request
Nov 25, 2026
…form MarkovSwitching.untransform_params inverted the logistic transform of the transition probabilities with scipy's root finder for three or more regimes, and raised "Could not untransform parameters." whenever it did not converge. It does not converge when a probability out of a regime is (nearly) zero, in particular the implied probability of moving to the last regime, one minus the sum of the others, which rounds to zero or to noise of about 1e-16. With the corrected EM step of statsmodels#11066, 20 EM iterations drive such a probability to zero, and MarkovRegression(y, 3).fit(em_iter=20) raised in 55 of 400 simulated samples (65 with em_iter=50). The same failure was reachable on main with start parameters such as p[0->0] = 0.3, p[0->1] = 0.7. The transform has a closed-form inverse: p[i->j] = exp(x_j) / (1 + sum_l exp(x_l)) gives x_j = log(p[i->j]) - log(p[i->k-1]), with p[i->k-1] = 1 - sum_j p[i->j]. This is also what the two-regime branch computed. Changes - untransform_params uses the closed form for any number of regimes. A probability of zero, including an implied last probability that is zero or slightly negative after rounding, is replaced by the smallest positive normal float (np.finfo(np.float64).tiny, about 2.2e-308) before taking logs, so the unconstrained parameters are finite (about 708 in size) and transform_params gives back the probabilities. Documented in the Notes, with a versionchanged directive. - Negative or NaN probabilities, or probabilities out of a regime that sum to more than one by more than 1e-8 (the tolerance of initialize_known), raise ValueError with a message that says so. With three or more regimes they raised "Could not untransform parameters." before; with two regimes they gave NaN. - The private _untransform_logistic, used only by the root finder, is removed; test_exog_tvtp computed the logits with it and now computes them directly. Fits that ran change only where the optimizer stops. On fedfunds (2 and 3 regimes), areturns (3 regimes), the Hamilton AR(4) and 40 simulated 3-regime samples, the unconstrained start parameters after the EM steps agree with those of the root finder to 6e-11 (relative) and the log-likelihood there to 5e-13; from them, the optimizer stops at another point of a flat likelihood in 4 of the 45 fits (log-likelihoods up to 8e-5 apart, parameters up to 3e-5 apart). With two regimes, a probability of exactly zero or one gave an infinite unconstrained parameter (one transformed back to NaN); they are finite now. Tests - Round trips untransform(transform(x)) and transform(untransform(p)) to rtol 1e-12 for 2, 3 and 4 regimes, with ordinary probabilities and with probabilities of 1e-22 and 1e-304. Fail on the base for 3 and 4 regimes ("Could not untransform parameters." with the tiny probabilities, and up to 4e-12 apart with the ordinary ones, the accuracy of the root finder). - Zero probabilities (explicit, implied, and a sum exceeding one by 1e-9) give finite unconstrained values that transform back to the probabilities; invalid ones (negative, NaN, a sum exceeding one by 1e-7) raise. - fit(em_iter=20, maxiter=0) for two simulated samples where the EM drives p[0->2] to zero (exactly, and to 8e-13) returns the EM parameters. Fails on the base ("Could not untransform parameters.").
bashtage
force-pushed
the
wip-ms-em-transition-denominator
branch
from
November 25, 2026 12:12
44887c9 to
1045c65
Compare
This was referenced Nov 25, 2026
bashtage
force-pushed
the
wip-ms-em-transition-denominator
branch
from
November 25, 2026 18:39
1045c65 to
617e3dd
Compare
bashtage
added a commit
to bashtage/statsmodels
that referenced
this pull request
Nov 25, 2026
…form MarkovSwitching.untransform_params inverted the logistic transform of the transition probabilities with scipy's root finder for three or more regimes, and raised "Could not untransform parameters." whenever it did not converge. It does not converge when a probability out of a regime is (nearly) zero, in particular the implied probability of moving to the last regime, one minus the sum of the others, which rounds to zero or to noise of about 1e-16. With the corrected EM step of statsmodels#11066, 20 EM iterations drive such a probability to zero, and MarkovRegression(y, 3).fit(em_iter=20) raised in 55 of 400 simulated samples (65 with em_iter=50). The same failure was reachable on main with start parameters such as p[0->0] = 0.3, p[0->1] = 0.7. The transform has a closed-form inverse: p[i->j] = exp(x_j) / (1 + sum_l exp(x_l)) gives x_j = log(p[i->j]) - log(p[i->k-1]), with p[i->k-1] = 1 - sum_j p[i->j]. This is also what the two-regime branch computed. Changes - untransform_params uses the closed form for any number of regimes. A probability of zero, including an implied last probability that is zero or slightly negative after rounding, is replaced by the smallest positive normal float (np.finfo(np.float64).tiny, about 2.2e-308) before taking logs, so the unconstrained parameters are finite (about 708 in size) and transform_params gives back the probabilities. Documented in the Notes, with a versionchanged directive. - Negative or NaN probabilities, or probabilities out of a regime that sum to more than one by more than 1e-8 (the tolerance of initialize_known), raise ValueError with a message that says so. With three or more regimes they raised "Could not untransform parameters." before; with two regimes they gave NaN. - The private _untransform_logistic, used only by the root finder, is removed; test_exog_tvtp computed the logits with it and now computes them directly. Fits that ran change only where the optimizer stops. On fedfunds (2 and 3 regimes), areturns (3 regimes), the Hamilton AR(4) and 40 simulated 3-regime samples, the unconstrained start parameters after the EM steps agree with those of the root finder to 6e-11 (relative) and the log-likelihood there to 5e-13; from them, the optimizer stops at another point of a flat likelihood in 4 of the 45 fits (log-likelihoods up to 8e-5 apart, parameters up to 3e-5 apart). With two regimes, a probability of exactly zero or one gave an infinite unconstrained parameter (one transformed back to NaN); they are finite now. Tests - Round trips untransform(transform(x)) and transform(untransform(p)) to rtol 1e-12 for 2, 3 and 4 regimes, with ordinary probabilities and with probabilities of 1e-22 and 1e-304. Fail on the base for 3 and 4 regimes ("Could not untransform parameters." with the tiny probabilities, and up to 4e-12 apart with the ordinary ones, the accuracy of the root finder). - Zero probabilities (explicit, implied, and a sum exceeding one by 1e-9) give finite unconstrained values that transform back to the probabilities; invalid ones (negative, NaN, a sum exceeding one by 1e-7) raise. - fit(em_iter=20, maxiter=0) for two simulated samples where the EM drives p[0->2] to zero (exactly, and to 8e-13) returns the EM parameters. Fails on the base ("Could not untransform parameters.").
bashtage
force-pushed
the
wip-ms-em-transition-denominator
branch
from
November 27, 2026 00:31
617e3dd to
3d1bf9f
Compare
bashtage
added a commit
to bashtage/statsmodels
that referenced
this pull request
Nov 27, 2026
…form MarkovSwitching.untransform_params inverted the logistic transform of the transition probabilities with scipy's root finder for three or more regimes, and raised "Could not untransform parameters." whenever it did not converge. It does not converge when a probability out of a regime is (nearly) zero, in particular the implied probability of moving to the last regime, one minus the sum of the others, which rounds to zero or to noise of about 1e-16. With the corrected EM step of statsmodels#11066, 20 EM iterations drive such a probability to zero, and MarkovRegression(y, 3).fit(em_iter=20) raised in 55 of 400 simulated samples (65 with em_iter=50). The same failure was reachable on main with start parameters such as p[0->0] = 0.3, p[0->1] = 0.7. The transform has a closed-form inverse: p[i->j] = exp(x_j) / (1 + sum_l exp(x_l)) gives x_j = log(p[i->j]) - log(p[i->k-1]), with p[i->k-1] = 1 - sum_j p[i->j]. This is also what the two-regime branch computed. Changes - untransform_params uses the closed form for any number of regimes. A probability of zero, including an implied last probability that is zero or slightly negative after rounding, is replaced by the smallest positive normal float (np.finfo(np.float64).tiny, about 2.2e-308) before taking logs, so the unconstrained parameters are finite (about 708 in size) and transform_params gives back the probabilities. Documented in the Notes, with a versionchanged directive. - Negative or NaN probabilities, or probabilities out of a regime that sum to more than one by more than 1e-8 (the tolerance of initialize_known), raise ValueError with a message that says so. With three or more regimes they raised "Could not untransform parameters." before; with two regimes they gave NaN. - The private _untransform_logistic, used only by the root finder, is removed; test_exog_tvtp computed the logits with it and now computes them directly. Fits that ran change only where the optimizer stops. On fedfunds (2 and 3 regimes), areturns (3 regimes), the Hamilton AR(4) and 40 simulated 3-regime samples, the unconstrained start parameters after the EM steps agree with those of the root finder to 6e-11 (relative) and the log-likelihood there to 5e-13; from them, the optimizer stops at another point of a flat likelihood in 4 of the 45 fits (log-likelihoods up to 8e-5 apart, parameters up to 3e-5 apart). With two regimes, a probability of exactly zero or one gave an infinite unconstrained parameter (one transformed back to NaN); they are finite now. Tests - Round trips untransform(transform(x)) and transform(untransform(p)) to rtol 1e-12 for 2, 3 and 4 regimes, with ordinary probabilities and with probabilities of 1e-22 and 1e-304. Fail on the base for 3 and 4 regimes ("Could not untransform parameters." with the tiny probabilities, and up to 4e-12 apart with the ordinary ones, the accuracy of the root finder). - Zero probabilities (explicit, implied, and a sum exceeding one by 1e-9) give finite unconstrained values that transform back to the probabilities; invalid ones (negative, NaN, a sum exceeding one by 1e-7) raise. - fit(em_iter=20, maxiter=0) for two simulated samples where the EM drives p[0->2] to zero (exactly, and to 8e-13) returns the EM parameters. Fails on the base ("Could not untransform parameters.").
bashtage
force-pushed
the
wip-ms-em-transition-denominator
branch
from
November 27, 2026 23:06
3d1bf9f to
3e57966
Compare
bashtage
added a commit
to bashtage/statsmodels
that referenced
this pull request
Nov 27, 2026
…form MarkovSwitching.untransform_params inverted the logistic transform of the transition probabilities with scipy's root finder for three or more regimes, and raised "Could not untransform parameters." whenever it did not converge. It does not converge when a probability out of a regime is (nearly) zero, in particular the implied probability of moving to the last regime, one minus the sum of the others, which rounds to zero or to noise of about 1e-16. With the corrected EM step of statsmodels#11066, 20 EM iterations drive such a probability to zero, and MarkovRegression(y, 3).fit(em_iter=20) raised in 55 of 400 simulated samples (65 with em_iter=50). The same failure was reachable on main with start parameters such as p[0->0] = 0.3, p[0->1] = 0.7. The transform has a closed-form inverse: p[i->j] = exp(x_j) / (1 + sum_l exp(x_l)) gives x_j = log(p[i->j]) - log(p[i->k-1]), with p[i->k-1] = 1 - sum_j p[i->j]. This is also what the two-regime branch computed. Changes - untransform_params uses the closed form for any number of regimes. A probability of zero, including an implied last probability that is zero or slightly negative after rounding, is replaced by the smallest positive normal float (np.finfo(np.float64).tiny, about 2.2e-308) before taking logs, so the unconstrained parameters are finite (about 708 in size) and transform_params gives back the probabilities. Documented in the Notes, with a versionchanged directive. - Negative or NaN probabilities, or probabilities out of a regime that sum to more than one by more than 1e-8 (the tolerance of initialize_known), raise ValueError with a message that says so. With three or more regimes they raised "Could not untransform parameters." before; with two regimes they gave NaN. - The private _untransform_logistic, used only by the root finder, is removed; test_exog_tvtp computed the logits with it and now computes them directly. Fits that ran change only where the optimizer stops. On fedfunds (2 and 3 regimes), areturns (3 regimes), the Hamilton AR(4) and 40 simulated 3-regime samples, the unconstrained start parameters after the EM steps agree with those of the root finder to 6e-11 (relative) and the log-likelihood there to 5e-13; from them, the optimizer stops at another point of a flat likelihood in 4 of the 45 fits (log-likelihoods up to 8e-5 apart, parameters up to 3e-5 apart). With two regimes, a probability of exactly zero or one gave an infinite unconstrained parameter (one transformed back to NaN); they are finite now. Tests - Round trips untransform(transform(x)) and transform(untransform(p)) to rtol 1e-12 for 2, 3 and 4 regimes, with ordinary probabilities and with probabilities of 1e-22 and 1e-304. Fail on the base for 3 and 4 regimes ("Could not untransform parameters." with the tiny probabilities, and up to 4e-12 apart with the ordinary ones, the accuracy of the root finder). - Zero probabilities (explicit, implied, and a sum exceeding one by 1e-9) give finite unconstrained values that transform back to the probabilities; invalid ones (negative, NaN, a sum exceeding one by 1e-7) raise. - fit(em_iter=20, maxiter=0) for two simulated samples where the EM drives p[0->2] to zero (exactly, and to 8e-13) returns the EM parameters. Fails on the base ("Could not untransform parameters.").
The EM step for the transition probabilities of the Markov switching
models (_em_regime_transition, used by fit with em_iter, the default
start, and by the start-parameter search with search_iter) estimated
p[i->j] = sum_t Pr[S_t = j, S_{t-1} = i | T] / sum_t Pr[S_t = i | T].
The M-step divides by sum_t Pr[S_{t-1} = i | T] (Hamilton, 1990). The two
sums differ by Pr[S_{T-1} = i | T] - Pr[S_{-1} = i | T], up to one
observation in each regime, so the estimates were off by about 1/nobs:
by 0.35% at the start parameters of fedfunds[-10:], and by 1.4% to 13% in
the new tests, whose short series (18 and 20 observations) end in another
regime than they start. The rows of the estimated matrix need not sum
to one, which is what the "Invalid regime transition probabilities"
rescaling was there for.
Changes
- Divide by the sum of the smoothed joint probabilities over S_t, that is
sum_t Pr[S_{t-1} = i | T]. The rows sum to one.
- versionchanged in the em_iter docstring of fit.
Results change. Of the 11 test_fit_em regression values (statsmodels'
own EM with its default settings, no external reference), 8 rise, for
example -745.83654 to -745.82796 (areturns) and -508.65852 to -508.65687
(fedfunds). Two fall slightly because the EM stops on its tolerance at
another point of its path: TestHamiltonAR4 by 1.9e-5 (3 iterations) and
TestFedFundsConstL1Exog by 6.8e-5 (run to the end, both versions reach
-229.25616). TestHamiltonAR2Short (10 observations) falls from -8.886 to
-49.95, because the last M-step of the AR coefficients jumps to explosive
values. Fitted results change where the optimizer starts from the EM
parameters and stops at another point: the 10-observation fedfunds model
now reaches a degenerate maximum (llf 5.127, one regime for the first
observation and a variance near zero) instead of -7.855, the 10-observation
AR(2) another local maximum (-5.096 instead of -4.052), and the Hamilton
switching AR(2) -179.386805 instead of -179.386841.
Not changed
- The EM steps of the other parameters, and models with time-varying
transition probabilities (the EM does not update them).
- The rescaling when a row sums to more than one. With the fixed
denominator, it can only happen by rounding; no test reaches it now.
Tests
- test_em_transition_m_step (MarkovRegression with 2 and 3 regimes,
MarkovAutoregression of order 2): one EM iteration through
fit(em_iter=1, maxiter=0) gives the transition probabilities computed in
the test from the smoothed joint probabilities at the start parameters.
Fails on main.
- The 11 test_fit_em values are recomputed (10 fail on main; AR4 was
within the tolerance), with a comment that they are regression values.
- test_fit of TestHamiltonAR2Short, TestFedFundsConstShort and
TestHamiltonAR2Switch passes the start parameters that 5 EM iterations
gave on main (em_iter=0), so they keep checking the same optimum.
bashtage
force-pushed
the
wip-ms-em-transition-denominator
branch
from
November 28, 2026 21:36
3e57966 to
b30b659
Compare
bashtage
added a commit
to bashtage/statsmodels
that referenced
this pull request
Nov 28, 2026
…form MarkovSwitching.untransform_params inverted the logistic transform of the transition probabilities with scipy's root finder for three or more regimes, and raised "Could not untransform parameters." whenever it did not converge. It does not converge when a probability out of a regime is (nearly) zero, in particular the implied probability of moving to the last regime, one minus the sum of the others, which rounds to zero or to noise of about 1e-16. With the corrected EM step of statsmodels#11066, 20 EM iterations drive such a probability to zero, and MarkovRegression(y, 3).fit(em_iter=20) raised in 55 of 400 simulated samples (65 with em_iter=50). The same failure was reachable on main with start parameters such as p[0->0] = 0.3, p[0->1] = 0.7. The transform has a closed-form inverse: p[i->j] = exp(x_j) / (1 + sum_l exp(x_l)) gives x_j = log(p[i->j]) - log(p[i->k-1]), with p[i->k-1] = 1 - sum_j p[i->j]. This is also what the two-regime branch computed. Changes - untransform_params uses the closed form for any number of regimes. A probability of zero, including an implied last probability that is zero or slightly negative after rounding, is replaced by the smallest positive normal float (np.finfo(np.float64).tiny, about 2.2e-308) before taking logs, so the unconstrained parameters are finite (about 708 in size) and transform_params gives back the probabilities. Documented in the Notes, with a versionchanged directive. - Negative or NaN probabilities, or probabilities out of a regime that sum to more than one by more than 1e-8 (the tolerance of initialize_known), raise ValueError with a message that says so. With three or more regimes they raised "Could not untransform parameters." before; with two regimes they gave NaN. - The private _untransform_logistic, used only by the root finder, is removed; test_exog_tvtp computed the logits with it and now computes them directly. Fits that ran change only where the optimizer stops. On fedfunds (2 and 3 regimes), areturns (3 regimes), the Hamilton AR(4) and 40 simulated 3-regime samples, the unconstrained start parameters after the EM steps agree with those of the root finder to 6e-11 (relative) and the log-likelihood there to 5e-13; from them, the optimizer stops at another point of a flat likelihood in 4 of the 45 fits (log-likelihoods up to 8e-5 apart, parameters up to 3e-5 apart). With two regimes, a probability of exactly zero or one gave an infinite unconstrained parameter (one transformed back to NaN); they are finite now. Tests - Round trips untransform(transform(x)) and transform(untransform(p)) to rtol 1e-12 for 2, 3 and 4 regimes, with ordinary probabilities and with probabilities of 1e-22 and 1e-304. Fail on the base for 3 and 4 regimes ("Could not untransform parameters." with the tiny probabilities, and up to 4e-12 apart with the ordinary ones, the accuracy of the root finder). - Zero probabilities (explicit, implied, and a sum exceeding one by 1e-9) give finite unconstrained values that transform back to the probabilities; invalid ones (negative, NaN, a sum exceeding one by 1e-7) raise. - fit(em_iter=20, maxiter=0) for two simulated samples where the EM drives p[0->2] to zero (exactly, and to 8e-13) returns the EM parameters. Fails on the base ("Could not untransform parameters.").
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Merge together with #11183 (decision 75): with this PR alone,
MarkovRegression(y, 3).fit(em_iter=20)raises "Could not untransform parameters." in 55 of 400 simulated samples, because the corrected EM drives a transition probability to about 1e-22; #11183 (stacked on this PR) inverts the transform in closed form.#10977 (the C7a chunk) rewrites the
em_iterdocstring offit; after both merge it should read "Number of initial EM iteration steps used to improve starting parameters. Not used if the model has time-varying transition probabilities. Default is 5." followed by this PR'sversionchanged. #10994, #11008 and #11012 also append totest_markov_autoregression.py, and the robust-rank PR totest_markov_regression.py: keep every appended block.The EM step for the transition probabilities of the Markov switching
models (_em_regime_transition, used by fit with em_iter, the default
start, and by the start-parameter search with search_iter) estimated
p[i->j] = sum_t Pr[S_t = j, S_{t-1} = i | T] / sum_t Pr[S_t = i | T].
The M-step divides by sum_t Pr[S_{t-1} = i | T] (Hamilton, 1990). The two
sums differ by Pr[S_{T-1} = i | T] - Pr[S_{-1} = i | T], up to one
observation in each regime, so the estimates were off by about 1/nobs:
by 0.35% at the start parameters of fedfunds[-10:], and by 1.4% to 13% in
the new tests, whose short series (18 and 20 observations) end in another
regime than they start. The rows of the estimated matrix need not sum
to one, which is what the "Invalid regime transition probabilities"
rescaling was there for.
Changes
sum_t Pr[S_{t-1} = i | T]. The rows sum to one.
Results change. Of the 11 test_fit_em regression values (statsmodels'
own EM with its default settings, no external reference), 8 rise, for
example -745.83654 to -745.82796 (areturns) and -508.65852 to -508.65687
(fedfunds). Two fall slightly because the EM stops on its tolerance at
another point of its path: TestHamiltonAR4 by 1.9e-5 (3 iterations) and
TestFedFundsConstL1Exog by 6.8e-5 (run to the end, both versions reach
-229.25616). TestHamiltonAR2Short (10 observations) falls from -8.886 to
-49.95, because the last M-step of the AR coefficients jumps to explosive
values. Fitted results change where the optimizer starts from the EM
parameters and stops at another point: the 10-observation fedfunds model
now reaches a degenerate maximum (llf 5.127, one regime for the first
observation and a variance near zero) instead of -7.855, the 10-observation
AR(2) another local maximum (-5.096 instead of -4.052), and the Hamilton
switching AR(2) -179.386805 instead of -179.386841.
Not changed
transition probabilities (the EM does not update them).
denominator, it can only happen by rounding; no test reaches it now.
Tests
test_em_transition_m_step (MarkovRegression with 2 and 3 regimes,
MarkovAutoregression of order 2): one EM iteration through
fit(em_iter=1, maxiter=0) gives the transition probabilities computed in
the test from the smoothed joint probabilities at the start parameters.
Fails on main.
The 11 test_fit_em values are recomputed (10 fail on main; AR4 was
within the tolerance), with a comment that they are regression values.
test_fit of TestHamiltonAR2Short, TestFedFundsConstShort and
TestHamiltonAR2Switch passes the start parameters that 5 EM iterations
gave on main (em_iter=0), so they keep checking the same optimum.
tests added / passed.
code/documentation is well formatted.
properly formatted commit message. See
NumPy's guide.
AI Disclosure
Contributions must comply with the statsmodels AI Policy.
Tick exactly one of the following. If AI tools were used, replace the
<...>placeholders in the second option with the tool name(s) and how the tool's output was
used.
Tool(s): Claude Code (Claude Opus 5.5).
Used for: finding the bug in a contract audit, writing the fix and its tests, and checking them (tests failing on main, mutation check).
I have personally read, understood, and can explain every line of this diff, and
have verified the statistical/numerical correctness of the change.
🤖 Generated with Claude Code