Skip to content

ENH: improved of the ProcessMLE(loglike, score) class 16 times faster - #9264

Closed
quant12345 wants to merge 7 commits into
statsmodels:mainfrom
quant12345:process_mle
Closed

quant12345 wants to merge 7 commits into
statsmodels:mainfrom
quant12345:process_mle

Conversation

@quant12345

@quant12345 quant12345 commented Jun 1, 2024 •

Copy link
Copy Markdown
Contributor
  • tests added / passed.
  • code/documentation is well formatted.
  • properly formatted commit message. See
    NumPy's guide.

This PR reduces the calculation time of methods: loglike, score from the class: ProcessMLE. Speedup of test_formulas is 16 times on average. To achieve this performance eliminated loops in which the methods are called: get_cov, jac from the GaussianCovariance class(these methods are also optimized).

The main idea is this: take the ind indexes that were used in the loop and select the necessary elements using np.take. And using np.newaxis do the calculation for each line.I added the jac_all method because the jac method is big enough and what I did in get_cov with the if time.ndim == 1 check: would make it even bigger.
To reduce the number of operations of the same type, a method has been added: similar_code.

There was a bug in: LinuxTest python_312_pre, which has been fixed (see comment).

Test times before and after.
before:

26.02s call     statsmodels/regression/tests/test_processreg.py::test_formulas[True]
23.09s call     statsmodels/regression/tests/test_processreg.py::test_arrays[True]
18.56s call     statsmodels/regression/tests/test_processreg.py::test_formulas[False]
18.18s call     statsmodels/regression/tests/test_processreg.py::test_arrays[False]
3.05s call     statsmodels/regression/tests/test_processreg.py::test_score_numdiff[True]
2.80s call     statsmodels/regression/tests/test_processreg.py::test_score_numdiff[False]

after:

1.79s call     statsmodels/regression/tests/test_processreg.py::test_formulas[True]
1.50s call     statsmodels/regression/tests/test_processreg.py::test_arrays[True]
1.60s call     statsmodels/regression/tests/test_processreg.py::test_formulas[False]
1.22s call     statsmodels/regression/tests/test_processreg.py::test_arrays[False]
0.32s call     statsmodels/regression/tests/test_processreg.py::test_score_numdiff[True]
0.28s call     statsmodels/regression/tests/test_processreg.py::test_score_numdiff[False]

What are the community's thoughts?

To compare performance, I created a separate process_regression_ file, which I have included in the attachment. It calls ProcessMLE_new and ProcessMLE for comparison. Place process_regression_ in the main directory and use the following code to test:

test_processreg
from statsmodels.compat.platform import PLATFORM_OSX

from process_regression_ import (
    ProcessMLE, ProcessMLE_new, GaussianCovariance)
import numpy as np
import pandas as pd
import pytest

import collections
import statsmodels.tools.numdiff as nd
from numpy.testing import assert_allclose, assert_equal


# Parameters for a test model, with or without additive
# noise.
def model1(noise):
    mn_par = np.r_[1, 0, -1, 0]
    sc_par = np.r_[1, 1]
    sm_par = np.r_[0.5, 0.1]

    if noise:
        no_par = np.r_[0.25, 0.25]
    else:
        no_par = np.array([])

    return mn_par, sc_par, sm_par, no_par


def setup1(n, get_model, noise):
    mn_par, sc_par, sm_par, no_par = get_model(noise)

    groups = np.kron(np.arange(n // 5), np.ones(5))
    time = np.kron(np.ones(n // 5), np.arange(5))
    time_z = (time - time.mean()) / time.std()

    x_mean = np.random.normal(size=(n, len(mn_par)))
    x_sc = np.random.normal(size=(n, len(sc_par)))
    x_sc[:, 0] = 1
    x_sc[:, 1] = time_z
    x_sm = np.random.normal(size=(n, len(sm_par)))
    x_sm[:, 0] = 1
    x_sm[:, 1] = time_z

    mn = np.dot(x_mean, mn_par)
    sc = np.exp(np.dot(x_sc, sc_par))
    sm = np.exp(np.dot(x_sm, sm_par))

    if noise:
        x_no = np.random.normal(size=(n, len(no_par)))
        x_no[:, 0] = 1
        x_no[:, 1] = time_z
        no = np.exp(np.dot(x_no, no_par))
    else:
        x_no = None

    y = mn.copy()

    gc = GaussianCovariance()

    ix = collections.defaultdict(list)
    for i, g in enumerate(groups):
        ix[g].append(i)

    for g, ii in ix.items():
        c = gc.get_cov(time[ii], sc[ii], sm[ii])
        r = np.linalg.cholesky(c)
        y[ii] += np.dot(r, np.random.normal(size=len(ii)))

    # Additive white noise
    if noise:
        y += no * np.random.normal(size=y.shape)

    return y, x_mean, x_sc, x_sm, x_no, time, groups


def run_arrays_new(n, get_model, noise):
    y, x_mean, x_sc, x_sm, x_no, time, groups = setup1(n, get_model, noise)

    preg = ProcessMLE_new(y, x_mean, x_sc, x_sm, x_no, time, groups)

    return preg.fit()


@pytest.mark.slow
@pytest.mark.parametrize("noise", [False, True])
def test_arrays_new(noise, n):
    np.random.seed(8234)

    f = run_arrays_new(n, model1, noise)
    mod = f.model

    f.summary()  # Smoke test

    # Compare the parameter estimates to population values.
    epar = np.concatenate(model1(noise))
    assert_allclose(f.params, epar, atol=0.3, rtol=0.3)

    # Test the fitted covariance matrix
    cv = f.covariance(mod.time[0:5], mod.exog_scale[0:5, :],
                      mod.exog_smooth[0:5, :])
    assert_allclose(cv, cv.T)  # Check symmetry
    a, _ = np.linalg.eig(cv)
    assert_equal(a > 0, True)  # Check PSD

    # Test predict
    yhat = f.predict()
    assert_equal(np.corrcoef(yhat, mod.endog)[0, 1] > 0.2, True)
    yhatm = f.predict(exog=mod.exog)
    assert_allclose(yhat, yhatm, rtol=1e-10)
    yhat0 = mod.predict(params=f.params, exog=mod.exog)
    assert_allclose(yhat, yhat0, rtol=1e-10)

    # Smoke test t-test
    f.t_test(np.eye(len(f.params)))


def run_arrays(n, get_model, noise):
    y, x_mean, x_sc, x_sm, x_no, time, groups = setup1(n, get_model, noise)

    preg = ProcessMLE(y, x_mean, x_sc, x_sm, x_no, time, groups)

    return preg.fit()


@pytest.mark.slow
@pytest.mark.parametrize("noise", [False, True])
def test_arrays(noise, n):
    np.random.seed(8234)

    f = run_arrays(n, model1, noise)
    mod = f.model

    f.summary()  # Smoke test

    # Compare the parameter estimates to population values.
    epar = np.concatenate(model1(noise))
    assert_allclose(f.params, epar, atol=0.3, rtol=0.3)

    # Test the fitted covariance matrix
    cv = f.covariance(mod.time[0:5], mod.exog_scale[0:5, :],
                      mod.exog_smooth[0:5, :])
    assert_allclose(cv, cv.T)  # Check symmetry
    a, _ = np.linalg.eig(cv)
    assert_equal(a > 0, True)  # Check PSD

    # Test predict
    yhat = f.predict()
    assert_equal(np.corrcoef(yhat, mod.endog)[0, 1] > 0.2, True)
    yhatm = f.predict(exog=mod.exog)
    assert_allclose(yhat, yhatm, rtol=1e-10)
    yhat0 = mod.predict(params=f.params, exog=mod.exog)
    assert_allclose(yhat, yhat0, rtol=1e-10)

    # Smoke test t-test
    f.t_test(np.eye(len(f.params)))


def run_formula_new(n, get_model, noise):
    y, x_mean, x_sc, x_sm, x_no, time, groups = setup1(n, get_model, noise)

    df = pd.DataFrame({
        "y": y,
        "x1": x_mean[:, 0],
        "x2": x_mean[:, 1],
        "x3": x_mean[:, 2],
        "x4": x_mean[:, 3],
        "xsc1": x_sc[:, 0],
        "xsc2": x_sc[:, 1],
        "xsm1": x_sm[:, 0],
        "xsm2": x_sm[:, 1],
        "time": time,
        "groups": groups
    })

    if noise:
        df["xno1"] = x_no[:, 0]
        df["xno2"] = x_no[:, 1]

    mean_formula = "y ~ 0 + x1 + x2 + x3 + x4"
    scale_formula = "0 + xsc1 + xsc2"
    smooth_formula = "0 + xsm1 + xsm2"

    if noise:
        noise_formula = "0 + xno1 + xno2"
    else:
        noise_formula = None

    preg = ProcessMLE_new.from_formula(
        mean_formula,
        data=df,
        scale_formula=scale_formula,
        smooth_formula=smooth_formula,
        noise_formula=noise_formula,
        time="time",
        groups="groups")
    f = preg.fit()

    return f, df


@pytest.mark.slow
@pytest.mark.parametrize("noise", [False, True])
def test_formulas_new(noise, n):

    np.random.seed(8789)

    f, df = run_formula_new(n, model1, noise)
    mod = f.model

    f.summary()  # Smoke test

    # Compare the parameter estimates to population values.
    epar = np.concatenate(model1(noise))
    assert_allclose(f.params, epar, atol=0.1, rtol=1)

    # Test the fitted covariance matrix
    exog_scale = pd.DataFrame(mod.exog_scale[0:5, :],
                              columns=["xsc1", "xsc2"])
    exog_smooth = pd.DataFrame(mod.exog_smooth[0:5, :],
                               columns=["xsm1", "xsm2"])
    cv = f.covariance(mod.time[0:5], exog_scale, exog_smooth)

    assert_allclose(cv, cv.T)
    a, _ = np.linalg.eig(cv)
    assert_equal(a > 0, True)

    # Test predict
    yhat = f.predict()
    assert_equal(np.corrcoef(yhat, mod.endog)[0, 1] > 0.2, True)
    yhatm = f.predict(exog=df)
    assert_allclose(yhat, yhatm, rtol=1e-10)
    yhat0 = mod.predict(params=f.params, exog=df)
    assert_allclose(yhat, yhat0, rtol=1e-10)

    # Smoke test t-test
    f.t_test(np.eye(len(f.params)))


def run_formula(n, get_model, noise):
    y, x_mean, x_sc, x_sm, x_no, time, groups = setup1(n, get_model, noise)

    df = pd.DataFrame({
        "y": y,
        "x1": x_mean[:, 0],
        "x2": x_mean[:, 1],
        "x3": x_mean[:, 2],
        "x4": x_mean[:, 3],
        "xsc1": x_sc[:, 0],
        "xsc2": x_sc[:, 1],
        "xsm1": x_sm[:, 0],
        "xsm2": x_sm[:, 1],
        "time": time,
        "groups": groups
    })

    if noise:
        df["xno1"] = x_no[:, 0]
        df["xno2"] = x_no[:, 1]

    mean_formula = "y ~ 0 + x1 + x2 + x3 + x4"
    scale_formula = "0 + xsc1 + xsc2"
    smooth_formula = "0 + xsm1 + xsm2"

    if noise:
        noise_formula = "0 + xno1 + xno2"
    else:
        noise_formula = None

    preg = ProcessMLE.from_formula(
        mean_formula,
        data=df,
        scale_formula=scale_formula,
        smooth_formula=smooth_formula,
        noise_formula=noise_formula,
        time="time",
        groups="groups")
    f = preg.fit()

    return f, df


@pytest.mark.slow
@pytest.mark.parametrize("noise", [False, True])
def test_formulas(noise, n):

    np.random.seed(8789)

    f, df = run_formula(n, model1, noise)
    mod = f.model

    f.summary()  # Smoke test

    # Compare the parameter estimates to population values.
    epar = np.concatenate(model1(noise))
    assert_allclose(f.params, epar, atol=0.1, rtol=1)

    # Test the fitted covariance matrix
    exog_scale = pd.DataFrame(mod.exog_scale[0:5, :],
                              columns=["xsc1", "xsc2"])
    exog_smooth = pd.DataFrame(mod.exog_smooth[0:5, :],
                               columns=["xsm1", "xsm2"])
    cv = f.covariance(mod.time[0:5], exog_scale, exog_smooth)
    assert_allclose(cv, cv.T)
    a, _ = np.linalg.eig(cv)
    assert_equal(a > 0, True)

    # Test predict
    yhat = f.predict()
    assert_equal(np.corrcoef(yhat, mod.endog)[0, 1] > 0.2, True)
    yhatm = f.predict(exog=df)
    assert_allclose(yhat, yhatm, rtol=1e-10)
    yhat0 = mod.predict(params=f.params, exog=df)
    assert_allclose(yhat, yhat0, rtol=1e-10)

    # Smoke test t-test
    f.t_test(np.eye(len(f.params)))


# Test the score functions using numerical derivatives.
@pytest.mark.parametrize("noise", [False, True])
def test_score_numdiff_new(noise, n):
    y, x_mean, x_sc, x_sm, x_no, time, groups = setup1(n, model1, noise)

    preg = ProcessMLE_new(y, x_mean, x_sc, x_sm, x_no, time, groups)

    def loglike(x):
        return preg.loglike(x)

    q = x_mean.shape[1] + x_sc.shape[1] + x_sm.shape[1]
    if noise:
        q += x_no.shape[1]

    np.random.seed(342)

    atol = 2e-3 if PLATFORM_OSX else 1e-2
    for _ in range(5):
        par0 = preg._get_start()
        par = par0 + 0.1 * np.random.normal(size=q)
        score = preg.score(par)
        score_nd = nd.approx_fprime(par, loglike, epsilon=1e-7)
        assert_allclose(score, score_nd, atol=atol, rtol=1e-4)


# Test the score functions using numerical derivatives.
@pytest.mark.parametrize("noise", [False, True])
def test_score_numdiff(noise, n):
    y, x_mean, x_sc, x_sm, x_no, time, groups = setup1(n, model1, noise)

    preg = ProcessMLE(y, x_mean, x_sc, x_sm, x_no, time, groups)

    def loglike(x):
        return preg.loglike(x)

    q = x_mean.shape[1] + x_sc.shape[1] + x_sm.shape[1]
    if noise:
        q += x_no.shape[1]

    np.random.seed(342)

    atol = 2e-3 if PLATFORM_OSX else 1e-2
    for _ in range(5):
        par0 = preg._get_start()
        par = par0 + 0.1 * np.random.normal(size=q)
        score = preg.score(par)
        score_nd = nd.approx_fprime(par, loglike, epsilon=1e-7)
        assert_allclose(score, score_nd, atol=atol, rtol=1e-4)


import datetime

n = 1000
noise = True

# '''
now = datetime.datetime.now()
test_formulas(noise, n)
time_old = datetime.datetime.now() - now
print('old', time_old)
# '''
now = datetime.datetime.now()
test_formulas_new(noise, n)
time_new = datetime.datetime.now() - now
print('new', time_new)

print('how many times faster', time_old / time_new)

Also in the attachment is the folder: processreg_comparison with which you canrun the old and new versions and compare their values ​​for equality (values ​​are rounded to the fifth character after the point).

process_regression_.zip
processreg_comparison.tar.gz

Details

Notes:

  • It is essential that you add a test when making code changes. Tests are not
    needed for doc changes.
  • When adding a new function, test values should usually be verified in another package (e.g., R/SAS/Stata).
  • When fixing a bug, you must add a test that would produce the bug in main and
    then show that it is fixed with the new code.
  • New code additions must be well formatted. Changes should pass flake8. If on Linux or OSX, you can
    verify you changes are well formatted by running
    git diff upstream/main -u -- "*.py" | flake8 --diff --isolated
    
    assuming flake8 is installed. This command is also available on Windows
    using the Windows System for Linux once flake8 is installed in the
    local Linux environment. While passing this test is not required, it is good practice and it help
    improve code quality in statsmodels.
  • Docstring additions must render correctly, including escapes and LaTeX.

loglike, score from class: ProcessMLE. Added methods jac_all (calculate all rows at once), added an option to get_cov (calculate all rows at once) and similar_code (same operations).
@quant12345

quant12345 commented Jun 1, 2024 •

Copy link
Copy Markdown
Contributor Author

In LinuxTest python_312_pre -> Run tests (pip pre)
an error occurs. In other versions everything works. Looking at List Configuration (PyPI) I saw that the
numpy version --- 2.1.0.dev0. The error occurs in: np.linalg.solve.

statsmodels/regression/process_regression.py:563: in loglike
    ls = np.linalg.solve(cm, resid_take)

statsmodels/regression/process_regression.py:627: in score
    dcr = np.linalg.solve(cm, resid_take)

ValueError: solve: Input operand 1 has a mismatch in its core dimension 0, with gufunc signature (m,m),(m,n)->(m,n) (size 200 is different from 5)

I think the problem is here (from the documentation):

The b array is only treated as a shape (M,) column vector if it is
 exactly 1-dimensional. In all other instances it is treated as a stack
 of (M, K) matrices. Previously b would be treated as a stack of (M,)
 vectors if b.ndim was equal to a.ndim - 1.

Asked in numpy.

The problem with numpy version --- 2.1.0.dev0 is solved.
before:

ls = np.linalg.solve(cm, resid_take)
dcr = np.linalg.solve(cm, resid_take)

after:

ls = (np.linalg.solve(cm, resid_take.reshape(200, 5, 1))
              .reshape(200, 5))
dcr = (np.linalg.solve(cm, resid_take.reshape(200, 5, 1))
               .reshape(200, 5))

@quant12345 quant12345 changed the title ENH: improved the performance of the ProcessMLE(loglike, score) class by 16 times ENH: improved the performance of the ProcessMLE(loglike, score) class 16 times faster Jun 1, 2024
@quant12345 quant12345 changed the title ENH: improved the performance of the ProcessMLE(loglike, score) class 16 times faster ENH: improved of the ProcessMLE(loglike, score) class 16 times faster Jun 1, 2024
Removing a long line
@pep8speaks

pep8speaks commented Jun 1, 2024 •

Copy link
Copy Markdown

Hello @quant12345! Thanks for updating this PR. We checked the lines you've touched for PEP 8 issues, and found:

There are currently no PEP 8 issues detected in this Pull Request. Cheers! 🍻

Comment last updated at 2024-06-04 14:56:43 UTC

quant12345 and others added 4 commits June 2, 2024 21:35
Changes for np.linalg.solve in new numpy versions. Trying to remove trailing spaces.
# Conflicts:
#	statsmodels/regression/process_regression.py
@josef-pkt josef-pkt mentioned this pull request Jun 17, 2024
6 tasks
@quant12345 quant12345 closed this Mar 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants