Skip to content

API Reference

Order 3 Samplers

Implements a third-order Higher-Order Langevin Monte Carlo (HoLMC) sampler for Bayesian linear regression. The sampler uses an underdamped Langevin dynamics approach to generate posterior samples over model parameters.

Parameters

params : O3Params Parameter object containing integration coefficients and covariance settings. N : int Number of samples to draw. Required. seed : int, optional Random seed for reproducibility. show_progress : bool, default=True Whether to display a progress bar during sampling.

Source code in holmc/samplers/o3sampler.py
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
class HoLMCSamplerO3Regression:
    """
    Implements a third-order Higher-Order Langevin Monte Carlo (HoLMC) sampler
    for Bayesian linear regression. The sampler uses an underdamped Langevin
    dynamics approach to generate posterior samples over model parameters.

    Parameters
    ----------
    params : O3Params
        Parameter object containing integration coefficients and covariance
        settings.
    N : int
        Number of samples to draw. Required.
    seed : int, optional
        Random seed for reproducibility.
    show_progress : bool, default=True
        Whether to display a progress bar during sampling.
    """

    def __init__(
        self,
        params: O3Params,
        N: int = None,
        seed: int = None,
        show_progress: bool = True,
    ):
        self.p = params
        self.N = N
        self.seed = seed
        self.show_progress = show_progress
        if seed is not None:
            np.random.seed(seed)
        if N is None:
            raise ValueError("Number of samples 'N' must be provided.")

    def sample(
        self,
        X: np.ndarray,
        y: np.ndarray,
        lamb: float = None,
        theta_random: bool = True,
    ) -> np.ndarray:
        """
        Run the HoLMC sampler to draw posterior samples for Bayesian linear
        regression.

        Parameters
        ----------
        X : np.ndarray
            Design matrix of shape (n_samples, n_features).
        y : np.ndarray
            Response vector of shape (n_samples,) or (n_samples, 1).
        lamb : float
            Regularization (prior precision) parameter. Required.
        theta_random : bool, default=True
            If True, initializes theta randomly; otherwise uses the ridge
            solution.

        Returns
        -------
        samples : np.ndarray
            Array of shape (N+1, n_features) containing sampled parameter
            vectors.
        """
        if lamb is None:
            raise ValueError(
                "Regularization parameter 'lamb' must be provided."
            )
        eta = self.p.eta
        n, d = X.shape
        A = ((X.T @ X) / n) + lamb * np.eye(d)
        b = ((X.T @ y) / n).squeeze()
        L = self.p.L

        # mu parameters
        mu12, mu13 = self.p.mu12(), self.p.mu13()
        mu22, mu23 = self.p.mu22(), self.p.mu23()
        mu31, mu32 = self.p.mu31(), self.p.mu32()
        mu33 = self.p.mu33()

        # Covariance matrix
        Sigma = self.p.sigma(d)

        CL = np.linalg.cholesky(Sigma)

        # Initiate the states
        if theta_random:
            theta = np.random.randn(d)
        else:
            theta = np.linalg.solve(A, b)
        v1 = np.zeros_like(theta)
        v2 = np.zeros_like(theta)

        samples = []
        samples.append(theta.copy())

        for _ in tqdm(range(self.N), disable=not self.show_progress):
            mu = np.concatenate([theta, v1, v2])
            z = np.random.randn(3 * d)
            x = mu + CL @ z
            theta, v1, v2 = np.split(x, 3)

            # Updates in the mean vectors
            delta_f = (
                A @ (eta * theta + (np.power(eta, 2) / 2.0) * v1) - eta * b
            )

            theta = theta - (eta / (2.0 * L)) * delta_f + mu12 * v1 + mu13 * v2
            v1 = -(1 / L) * delta_f + mu22 * v1 + mu23 * v2
            v2 = (mu31 / L) * delta_f + mu32 * v1 + mu33 * v2

            samples.append(theta.copy())
        return np.array(samples)

sample(X, y, lamb=None, theta_random=True)

Run the HoLMC sampler to draw posterior samples for Bayesian linear regression.

Parameters

X : np.ndarray Design matrix of shape (n_samples, n_features). y : np.ndarray Response vector of shape (n_samples,) or (n_samples, 1). lamb : float Regularization (prior precision) parameter. Required. theta_random : bool, default=True If True, initializes theta randomly; otherwise uses the ridge solution.

Returns

samples : np.ndarray Array of shape (N+1, n_features) containing sampled parameter vectors.

Source code in holmc/samplers/o3sampler.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
def sample(
    self,
    X: np.ndarray,
    y: np.ndarray,
    lamb: float = None,
    theta_random: bool = True,
) -> np.ndarray:
    """
    Run the HoLMC sampler to draw posterior samples for Bayesian linear
    regression.

    Parameters
    ----------
    X : np.ndarray
        Design matrix of shape (n_samples, n_features).
    y : np.ndarray
        Response vector of shape (n_samples,) or (n_samples, 1).
    lamb : float
        Regularization (prior precision) parameter. Required.
    theta_random : bool, default=True
        If True, initializes theta randomly; otherwise uses the ridge
        solution.

    Returns
    -------
    samples : np.ndarray
        Array of shape (N+1, n_features) containing sampled parameter
        vectors.
    """
    if lamb is None:
        raise ValueError(
            "Regularization parameter 'lamb' must be provided."
        )
    eta = self.p.eta
    n, d = X.shape
    A = ((X.T @ X) / n) + lamb * np.eye(d)
    b = ((X.T @ y) / n).squeeze()
    L = self.p.L

    # mu parameters
    mu12, mu13 = self.p.mu12(), self.p.mu13()
    mu22, mu23 = self.p.mu22(), self.p.mu23()
    mu31, mu32 = self.p.mu31(), self.p.mu32()
    mu33 = self.p.mu33()

    # Covariance matrix
    Sigma = self.p.sigma(d)

    CL = np.linalg.cholesky(Sigma)

    # Initiate the states
    if theta_random:
        theta = np.random.randn(d)
    else:
        theta = np.linalg.solve(A, b)
    v1 = np.zeros_like(theta)
    v2 = np.zeros_like(theta)

    samples = []
    samples.append(theta.copy())

    for _ in tqdm(range(self.N), disable=not self.show_progress):
        mu = np.concatenate([theta, v1, v2])
        z = np.random.randn(3 * d)
        x = mu + CL @ z
        theta, v1, v2 = np.split(x, 3)

        # Updates in the mean vectors
        delta_f = (
            A @ (eta * theta + (np.power(eta, 2) / 2.0) * v1) - eta * b
        )

        theta = theta - (eta / (2.0 * L)) * delta_f + mu12 * v1 + mu13 * v2
        v1 = -(1 / L) * delta_f + mu22 * v1 + mu23 * v2
        v2 = (mu31 / L) * delta_f + mu32 * v1 + mu33 * v2

        samples.append(theta.copy())
    return np.array(samples)

Implements a third-order Higher-Order Langevin Monte Carlo (HoLMC) sampler for Bayesian logistic regression. This sampler uses higher-order approximations of the potential energy gradient to improve sampling efficiency in classification tasks.

Parameters

params : O3Params Parameter object containing integration coefficients and covariance settings. N : int Number of samples to draw. Required. seed : int Random seed for reproducibility. show_progress : bool, default=True Whether to display a progress bar during sampling.

Source code in holmc/samplers/o3sampler.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
class HoLMCSamplerO3Classification:
    """
    Implements a third-order Higher-Order Langevin Monte Carlo (HoLMC)
    sampler for Bayesian logistic regression. This sampler uses higher-order
    approximations of the potential energy gradient to improve sampling
    efficiency in classification tasks.

    Parameters
    ----------
    params : O3Params
        Parameter object containing integration coefficients and covariance
        settings.
    N : int
        Number of samples to draw. Required.
    seed : int
        Random seed for reproducibility.
    show_progress : bool, default=True
        Whether to display a progress bar during sampling.
    """

    def __init__(
        self,
        params: O3Params,
        N: int = None,
        seed: int = None,
        show_progress: bool = True,
    ):
        self.params = params
        self.N = N
        self.seed = seed
        self.show_progress = show_progress
        if seed is not None:
            np.random.seed(seed)
        if N is None:
            raise ValueError("Number of samples 'N' must be provided.")

    def sample(
        self, X: np.ndarray, y: np.ndarray, lamb: float = None
    ) -> np.ndarray:
        if lamb is None:
            raise ValueError(
                "Regularization parameter 'lamb' must be provided."
            )
        d = X.shape[1]
        eta = self.params.eta
        L = self.params.L

        # mu parameters
        mu12, mu13 = self.params.mu12(), self.params.mu13()
        mu22, mu23 = self.params.mu22(), self.params.mu23()
        mu31, mu32 = self.params.mu31(), self.params.mu32()
        mu33 = self.params.mu33()

        # Covariance matrix
        Sigma = self.params.sigma(d)

        CL = np.linalg.cholesky(Sigma)

        # Initiate the states
        theta = np.random.randn(d)
        # theta_star = np.random.randn(d)
        # for _ in range(self.N):
        #     g = gradient(theta_star, X, y, lamb)
        #     theta_star -= eta * g
        # theta = theta_star.copy()
        v1 = np.zeros_like(theta)
        v2 = np.zeros_like(theta)

        samples = []
        samples.append(theta.copy())

        for _ in tqdm(range(self.N), disable=not self.show_progress):
            # Sample from the multivariate normal distribution
            mu = np.concatenate([theta, v1, v2])
            z = np.random.randn(3 * d)
            x = mu + CL @ z
            theta, v1, v2 = np.split(x, 3)
            # Updates in the mean vectors
            s = sigmoid(X @ theta)
            xv1 = X @ v1
            deltaU = (
                eta * (lamb * theta + X.T @ (s - y))
                + (eta**2 / 2) * (X.T @ (s * (1 - s) * xv1) + lamb * v1)
                + (eta**3 / 6) * (X.T @ (s * (1 - s) * (1 - 2 * s) * xv1**2))
                + (eta**4 / 24)
                * (X.T @ (s * (1 - s) * (1 - 6 * s + 6 * s**2) * xv1**3))
            )
            theta = theta - (eta / (2.0 * L)) * deltaU + mu12 * v1 + mu13 * v2
            v1 = -(1 / L) * deltaU + mu22 * v1 + mu23 * v2
            v2 = (mu31 / L) * deltaU + mu32 * v1 + mu33 * v2

            samples.append(theta.copy())
        return np.array(samples)

Order 4 Samplers

Implements a fourth-order Higher-Order Langevin Monte Carlo (HoLMC) sampler for Bayesian linear regression. This sampler uses a 4-stage underdamped Langevin dynamics scheme to generate high-quality posterior samples from the Bayesian model.

Parameters

params : O4Params Parameter object containing algorithmic coefficients, step size (eta), and damping (gamma). N : int Number of MCMC samples to draw. Must be specified. seed : int Random seed for reproducibility. show_progress : bool, default=True Whether to display a progress bar during sampling.

Source code in holmc/samplers/o4sampler.py
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
class HoLMCSamplerO4Regression:
    """
    Implements a fourth-order Higher-Order Langevin Monte Carlo (HoLMC)
    sampler for Bayesian linear regression. This sampler uses a 4-stage
    underdamped Langevin dynamics scheme to generate high-quality posterior
    samples from the Bayesian model.

    Parameters
    ----------
    params : O4Params
        Parameter object containing algorithmic coefficients, step size (eta),
        and damping (gamma).
    N : int
        Number of MCMC samples to draw. Must be specified.
    seed : int
        Random seed for reproducibility.
    show_progress : bool, default=True
        Whether to display a progress bar during sampling.
    """

    def __init__(
        self,
        params: O4Params,
        N: int = None,
        seed: int = None,
        show_progress: bool = True,
    ):
        self.params = params
        self.N = N
        self.seed = seed
        self.show_progress = show_progress
        self.rg = Regression()
        if seed is not None:
            np.random.seed(seed)
        if N is None:
            raise ValueError("Number of samples 'N' must be provided.")

    def sample(
        self,
        X: np.ndarray,
        y: np.ndarray,
        lamb: float = None,
        theta_random: bool = True,
    ) -> np.ndarray:
        """
        Run the fourth-order HoLMC sampler to draw posterior samples for
        Bayesian linear regression.

        Parameters
        ----------
        X : np.ndarray
            Design matrix of shape (n_samples, n_features).
        y : np.ndarray
            Response vector of shape (n_samples,) or (n_samples, 1).
        lamb : float
            Ridge regularization parameter (controls the prior precision). Must
            be specified.
        theta_random : bool, default=True
            Whether to initialize theta randomly or from the ridge solution.

        Returns
        -------
        samples : np.ndarray
            Array of shape (N+1, n_features) containing the sequence of sampled
            parameter vectors.
        """
        if lamb is None:
            raise ValueError(
                "Regularization parameter 'lamb' must be provided."
            )
        gamma = self.params.gamma
        eta = self.params.eta
        n, d = X.shape
        A = ((X.T @ X) / n) + lamb * np.eye(d)
        b = ((X.T @ y) / n).squeeze()

        # mu parameters
        mu01, mu02 = self.params.mu01(), self.params.mu02()
        mu03, mu11 = self.params.mu03(), self.params.mu11()
        mu12, mu13 = self.params.mu12(), self.params.mu13()
        mu21, mu22 = self.params.mu21(), self.params.mu22()
        mu23, mu31 = self.params.mu23(), self.params.mu31()
        mu32, mu33 = self.params.mu32(), self.params.mu33()

        # Covariance matrix
        Sigma = self.params.sigma(d)
        CL = np.linalg.cholesky(Sigma)

        # Initiate the states
        if theta_random:
            theta = np.random.randn(d)
        else:
            theta = np.linalg.solve(A, b)
        v1 = np.zeros_like(theta)
        v2 = np.zeros_like(theta)
        v3 = np.zeros_like(theta)

        samples = []
        samples.append(theta.copy())

        for _ in tqdm(range(self.N), disable=not self.show_progress):
            mu = np.concatenate([theta, v1, v2, v3])
            z = np.random.randn(4 * d)
            x = mu + CL @ z
            theta, v1, v2, v3 = np.split(x, 4)

            # Update in the mean vectors
            theta = self.rg.update_theta(
                theta, v1, v2, v3, A, b, gamma, eta, mu01, mu02, mu03
            )
            v1 = self.rg.update_v1(
                theta, v1, v2, v3, A, b, gamma, eta, mu11, mu12, mu13
            )
            v2 = self.rg.update_v2(
                theta, v1, v2, v3, A, b, gamma, eta, mu21, mu22, mu23
            )
            v3 = self.rg.update_v3(
                theta, v1, v2, v3, A, b, gamma, eta, mu31, mu32, mu33
            )

            samples.append(theta.copy())
        return np.array(samples)

sample(X, y, lamb=None, theta_random=True)

Run the fourth-order HoLMC sampler to draw posterior samples for Bayesian linear regression.

Parameters

X : np.ndarray Design matrix of shape (n_samples, n_features). y : np.ndarray Response vector of shape (n_samples,) or (n_samples, 1). lamb : float Ridge regularization parameter (controls the prior precision). Must be specified. theta_random : bool, default=True Whether to initialize theta randomly or from the ridge solution.

Returns

samples : np.ndarray Array of shape (N+1, n_features) containing the sequence of sampled parameter vectors.

Source code in holmc/samplers/o4sampler.py
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def sample(
    self,
    X: np.ndarray,
    y: np.ndarray,
    lamb: float = None,
    theta_random: bool = True,
) -> np.ndarray:
    """
    Run the fourth-order HoLMC sampler to draw posterior samples for
    Bayesian linear regression.

    Parameters
    ----------
    X : np.ndarray
        Design matrix of shape (n_samples, n_features).
    y : np.ndarray
        Response vector of shape (n_samples,) or (n_samples, 1).
    lamb : float
        Ridge regularization parameter (controls the prior precision). Must
        be specified.
    theta_random : bool, default=True
        Whether to initialize theta randomly or from the ridge solution.

    Returns
    -------
    samples : np.ndarray
        Array of shape (N+1, n_features) containing the sequence of sampled
        parameter vectors.
    """
    if lamb is None:
        raise ValueError(
            "Regularization parameter 'lamb' must be provided."
        )
    gamma = self.params.gamma
    eta = self.params.eta
    n, d = X.shape
    A = ((X.T @ X) / n) + lamb * np.eye(d)
    b = ((X.T @ y) / n).squeeze()

    # mu parameters
    mu01, mu02 = self.params.mu01(), self.params.mu02()
    mu03, mu11 = self.params.mu03(), self.params.mu11()
    mu12, mu13 = self.params.mu12(), self.params.mu13()
    mu21, mu22 = self.params.mu21(), self.params.mu22()
    mu23, mu31 = self.params.mu23(), self.params.mu31()
    mu32, mu33 = self.params.mu32(), self.params.mu33()

    # Covariance matrix
    Sigma = self.params.sigma(d)
    CL = np.linalg.cholesky(Sigma)

    # Initiate the states
    if theta_random:
        theta = np.random.randn(d)
    else:
        theta = np.linalg.solve(A, b)
    v1 = np.zeros_like(theta)
    v2 = np.zeros_like(theta)
    v3 = np.zeros_like(theta)

    samples = []
    samples.append(theta.copy())

    for _ in tqdm(range(self.N), disable=not self.show_progress):
        mu = np.concatenate([theta, v1, v2, v3])
        z = np.random.randn(4 * d)
        x = mu + CL @ z
        theta, v1, v2, v3 = np.split(x, 4)

        # Update in the mean vectors
        theta = self.rg.update_theta(
            theta, v1, v2, v3, A, b, gamma, eta, mu01, mu02, mu03
        )
        v1 = self.rg.update_v1(
            theta, v1, v2, v3, A, b, gamma, eta, mu11, mu12, mu13
        )
        v2 = self.rg.update_v2(
            theta, v1, v2, v3, A, b, gamma, eta, mu21, mu22, mu23
        )
        v3 = self.rg.update_v3(
            theta, v1, v2, v3, A, b, gamma, eta, mu31, mu32, mu33
        )

        samples.append(theta.copy())
    return np.array(samples)

Implements a fourth-order Higher-Order Langevin Monte Carlo (HoLMC) sampler for Bayesian logistic regression. This sampler uses a high-order underdamped Langevin dynamic with correction terms up to the third derivative of the sigmoid to approximate the gradient of the posterior.

Parameters

params : O4Params Parameter object containing algorithmic coefficients, step size (eta), and damping (gamma). N : int Number of MCMC samples to draw. Must be specified. seed : int Random seed for reproducibility. show_progress : bool, default=True Whether to display a progress bar during sampling.

Source code in holmc/samplers/o4sampler.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
class HoLMCSamplerO4Classification:
    """
    Implements a fourth-order Higher-Order Langevin Monte Carlo (HoLMC) sampler
    for Bayesian logistic regression. This sampler uses a high-order
    underdamped Langevin dynamic with correction terms up to the third
    derivative of the sigmoid to approximate the gradient of the posterior.

    Parameters
    ----------
    params : O4Params
        Parameter object containing algorithmic coefficients, step size (eta),
        and damping (gamma).
    N : int
        Number of MCMC samples to draw. Must be specified.
    seed : int
        Random seed for reproducibility.
    show_progress : bool, default=True
        Whether to display a progress bar during sampling.
    """

    def __init__(
        self,
        params: O4Params,
        N: int = None,
        seed: int = None,
        show_progress: bool = True,
    ):
        self.params = params
        self.N = N
        self.seed = seed
        self.show_progress = show_progress
        self.cl = Classification()
        if seed is not None:
            np.random.seed(seed)
        if N is None:
            raise ValueError("Number of samples 'N' must be provided.")

    def sample(
        self, X: np.ndarray, y: np.ndarray, lamb: float = None
    ) -> np.ndarray:
        if lamb is None:
            raise ValueError(
                "Regularization parameter 'lamb' must be provided."
            )
        d = X.shape[1]
        eta = self.params.eta
        gamma = self.params.gamma

        # mu parameters
        mu01, mu02 = self.params.mu01(), self.params.mu02()
        mu03, mu11 = self.params.mu03(), self.params.mu11()
        mu12, mu13 = self.params.mu12(), self.params.mu13()
        mu21, mu22 = self.params.mu21(), self.params.mu22()
        mu23, mu31 = self.params.mu23(), self.params.mu31()
        mu32, mu33 = self.params.mu32(), self.params.mu33()

        # Covariance matrix
        Sigma = self.params.sigma(d)
        CL = np.linalg.cholesky(Sigma)

        # Initiate the states
        theta = np.random.randn(d)
        # theta_star = np.random.randn(d)
        # for _ in range(self.N):
        #     g = gradient(theta_star, X, y, lamb)
        #     theta_star -= eta * g
        # theta = theta_star.copy()
        v1 = np.zeros_like(theta)
        v2 = np.zeros_like(theta)
        v3 = np.zeros_like(theta)

        samples = []
        samples.append(theta.copy())

        for _ in tqdm(range(self.N), disable=not self.show_progress):
            mu = np.concatenate([theta, v1, v2, v3])
            z = np.random.randn(4 * d)
            x = mu + CL @ z
            theta, v1, v2, v3 = np.split(x, 4)
            # Updates in the mean vectors
            theta = self.cl.update_theta(
                theta, v1, v2, v3, X, y, gamma, eta, lamb, mu01, mu02, mu03
            )
            v1 = self.cl.update_v1(
                theta, v1, v2, v3, X, y, gamma, eta, lamb, mu11, mu12, mu13
            )
            v2 = self.cl.update_v2(
                theta, v1, v2, v3, X, y, gamma, eta, lamb, mu21, mu22, mu23
            )
            v3 = self.cl.update_v3(
                theta, v1, v2, v3, X, y, gamma, eta, lamb, mu31, mu32, mu33
            )

            samples.append(theta.copy())
        return np.array(samples)

Parameters

Source code in holmc/utils/params.py
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
class O3Params:
    def __init__(
        self,
        gamma: float = None,
        eta: float = None,
        xi: float = None,
        L: float = 1.0
    ):
        self.gamma = gamma
        self.eta = eta
        self.xi = xi
        self.L = L

    def mu12(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        val = (
            (1 + gamma**2 / xi**2) * eta
            - (gamma**2 / (2 * xi)) * eta**2
            - (gamma**2 / xi**3) * (1 - np.exp(-xi * eta))
        )
        return val

    def mu13(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        val = (gamma / xi) * eta + (gamma / xi**2) * (np.exp(-xi * eta) - 1)
        return val

    def mu22(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        val = 1 + (gamma**2 / xi**2) * (1 - xi * eta - np.exp(-xi * eta))
        return val

    def mu23(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        val = (gamma / xi) * (1 - np.exp(-xi * eta))
        return val

    def mu31(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        val = (gamma / xi) - (gamma / xi**2) * ((1 - np.exp(-xi * eta)) / eta)
        return val

    def mu32(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        val = (
            (gamma**3 / xi**2) * eta
            + (gamma**3 / xi**2) * eta * np.exp(-xi * eta)
            - (2 * gamma**3 / xi**3 + gamma / xi) * (1 - np.exp(-xi * eta))
        )
        return val

    def mu33(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        val = (
            np.exp(-xi * eta)
            + (gamma**2 / xi) * eta * np.exp(-xi * eta)
            - (gamma**2 / xi**2) * (1 - np.exp(-xi * eta))
        )
        return val

    # Sigma entries
    def sigma11(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        exp1 = np.exp(-eta * xi)
        exp2 = np.exp(-2 * eta * xi)
        val = (
            (2 * np.power(gamma, 2) * eta) / np.power(xi, 3)
            - (2 * np.power(gamma, 2) * np.power(eta, 2)) / np.power(xi, 2)
            + (2 * np.power(gamma, 2) * np.power(eta, 3)) / (3 * xi)
            - (4 * np.power(gamma, 2) * eta * exp1) / np.power(xi, 3)
            + (np.power(gamma, 2) * (1 - exp2)) / np.power(xi, 4)
        )
        return val

    def sigma12(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        L = self.L
        exp1 = np.exp(-eta * xi)
        val = (np.power(gamma, 2) * np.power((xi * eta - (1 - exp1)), 2)) / (
            np.power(xi, 3) * L
        )
        return val

    def sigma22(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        exp1 = np.exp(-eta * xi)
        exp2 = np.exp(-2 * eta * xi)
        val = (
            (2 * np.power(gamma, 2) * eta) / xi
            - (4 * np.power(gamma, 2) * (1 - exp1)) / np.power(xi, 2)
            + (np.power(gamma, 2) * (1 - exp2)) / np.power(xi, 2)
        )
        return val

    def sigma13(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        exp1 = np.exp(-eta * xi)
        exp2 = np.exp(-2 * eta * xi)
        val = (
            -(np.power(gamma, 3) * np.power(eta, 2) * (2 * exp1 + 1))
            / np.power(xi, 2)
            + eta
            * (
                (2 * np.power(gamma, 3)) / np.power(xi, 3)
                - (np.power(gamma, 3) * exp2) / np.power(xi, 3)
                - (4 * np.power(gamma, 3) * exp1) / np.power(xi, 3)
                - (2 * gamma * exp1) / xi
            )
            + (
                ((3 * np.power(gamma, 3)) / (2 * np.power(xi, 4)))
                + gamma / np.power(xi, 2)
            )
            * (1 - exp2)
        )
        return val

    def sigma23(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        exp1 = np.exp(-eta * xi)
        exp2 = np.exp(-2 * eta * xi)
        val = (
            (np.power(gamma, 3) * (exp2 - 2 * exp1 - 2) * eta)
            / np.power(xi, 2)
            + (3 * np.power(gamma, 3) * (exp2 - 4 * exp1 + 3))
            / (2 * np.power(xi, 3))
            + (gamma * np.power((1 - exp1), 2)) / xi
        )
        return val

    def sigma33(self):
        gamma = self.gamma
        eta = self.eta
        xi = self.xi
        exp1 = np.exp(-eta * xi)
        exp2 = np.exp(-2 * eta * xi)
        val = (
            -(np.power(gamma, 4) * np.power(eta, 2) * exp2) / np.power(xi, 2)
            + eta
            * (
                -(2 * np.power(gamma, 2) * exp2) / xi
                + (np.power(gamma, 4) * (-3 * exp2 + 4 * exp1 + 2))
                / np.power(xi, 3)
            )
            + (np.power(gamma, 4) * (-5 * exp2 + 16 * exp1 - 11))
            / (2 * np.power(xi, 4))
            + (
                (np.power(gamma, 2) * (-3 * exp2 + 4 * exp1 - 1))
                / np.power(xi, 2)
            )
            + (1 - exp2)
        )
        return val

    def sigma(self, d):
        s11 = self.sigma11()
        s12 = self.sigma12()
        s13 = self.sigma13()
        s22 = self.sigma22()
        s23 = self.sigma23()
        s33 = self.sigma33()
        I_d = np.eye(d)

        # Now construct the full (3*dim x 3*dim) matrix
        top = np.hstack([s11 * I_d, s12 * I_d, s13 * I_d])
        mid = np.hstack([s12 * I_d, s22 * I_d, s23 * I_d])
        bot = np.hstack([s13 * I_d, s23 * I_d, s33 * I_d])

        mat = np.vstack([top, mid, bot])
        epsilon = 0.00001
        matrix = mat + epsilon * np.eye(3 * d)

        return matrix
Source code in holmc/utils/params.py
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
class O4Params:
    def __init__(
        self,
        gamma: float = None,
        eta: float = None
    ):
        self.gamma = gamma
        self.eta = eta

    def mu01(self):
        gamma = self.gamma
        eta = self.eta
        term1 = eta
        term2 = -(gamma**2) * (eta**3) / 6
        term3 = (gamma**4) * (eta**5) / 120

        exp_term = -np.exp(-gamma * eta) / (gamma**5)
        constant_terms = (
            +1 / gamma**5
            - eta / gamma**4
            + eta**2 / (2 * gamma**3)
            - eta**3 / (6 * gamma**2)
            + eta**4 / (24 * gamma)
        )

        term4 = gamma**4 * (exp_term + constant_terms)
        val = term1 + term2 + term3 + term4
        return val

    def mu02(self):
        gamma = self.gamma
        eta = self.eta
        term1 = gamma * (eta**2) / 2
        term2 = -(gamma**3) * (eta**4) / 24

        bracket = (
            np.exp(-gamma * eta) / (gamma**4)
            - 1 / (gamma**4)
            + eta / (gamma**3)
            - eta**2 / (2 * gamma**2)
            + eta**3 / (6 * gamma)
        )

        term3 = -(gamma**3) * bracket
        val = term1 + term2 + term3

        return val

    def mu03(self):
        gamma = self.gamma
        eta = self.eta
        term1 = -(gamma**4) * (eta**5) / 120

        bracket1 = (
            -np.exp(-gamma * eta) / (gamma**3)
            + 1 / (gamma**3)
            - eta / (gamma**2)
            + eta**2 / (2 * gamma)
        )

        bracket2 = (
            -np.exp(-gamma * eta) / (gamma**5)
            + 1 / (gamma**5)
            - eta / (gamma**4)
            + eta**2 / (2 * gamma**3)
            - eta**3 / (6 * gamma**2)
            + eta**4 / (24 * gamma)
        )

        term2 = gamma**2 * bracket1
        term3 = -(gamma**4) * bracket2

        val = term1 + term2 + term3

        return val

    def mu11(self):
        gamma = self.gamma
        eta = self.eta
        term1 = 1
        term2 = -(gamma**2) * (eta**2) / 2
        term3 = (gamma**4) * (eta**4) / 24

        bracket = (
            np.exp(-gamma * eta) / (gamma**4)
            - 1 / (gamma**4)
            + eta / (gamma**3)
            - eta**2 / (2 * gamma**2)
            + eta**3 / (6 * gamma)
        )

        term4 = gamma**4 * bracket

        val = term1 + term2 + term3 + term4

        return val

    def mu12(self):
        gamma = self.gamma
        eta = self.eta
        term1 = gamma * eta
        term2 = -(gamma**3) * (eta**3) / 6

        bracket = (
            -np.exp(-gamma * eta) / (gamma**3)
            + 1 / (gamma**3)
            - eta / (gamma**2)
            + eta**2 / (2 * gamma)
        )

        term3 = -(gamma**3) * bracket

        val = term1 + term2 + term3

        return val

    def mu13(self):
        gamma = self.gamma
        eta = self.eta
        term1 = -(gamma**4) * (eta**4) / 24

        bracket1 = (
            np.exp(-gamma * eta) / (gamma**2) - 1 / (gamma**2) + eta / gamma
        )

        bracket2 = (
            np.exp(-gamma * eta) / (gamma**4)
            - 1 / (gamma**4)
            + eta / (gamma**3)
            - eta**2 / (2 * gamma**2)
            + eta**3 / (6 * gamma)
        )

        term2 = gamma**2 * bracket1
        term3 = -(gamma**4) * bracket2

        val = term1 + term2 + term3

        return val

    def mu21(self):
        gamma = self.gamma
        eta = self.eta
        # Leading terms
        term1 = -gamma * eta
        term2 = gamma**3 * eta**3 / 6
        term3 = -(gamma**5) * eta**5 / 120

        # First bracket (with gamma^5)
        bracket1 = (
            -np.exp(-gamma * eta) / gamma**5
            + 1 / gamma**5
            - eta / gamma**4
            + eta**2 / (2 * gamma**3)
            - eta**3 / (6 * gamma**2)
            + eta**4 / (24 * gamma)
        )
        term4 = -(gamma**5) * bracket1

        # Second bracket (with gamma^3)
        bracket2 = (
            -np.exp(-gamma * eta) / gamma**3
            + 1 / gamma**3
            - eta / gamma**2
            + eta**2 / (2 * gamma)
        )
        term5 = gamma**3 * bracket2

        # Third bracket (gamma^5 / 3!)
        bracket3 = (
            -6 * np.exp(-gamma * eta) / gamma**5
            + 6 / gamma**5
            - 6 * eta / gamma**4
            + 3 * eta**2 / gamma**3
            - eta**3 / gamma**2
            + eta**4 / (4 * gamma)
        )
        term6 = -(gamma**5 / 6) * bracket3

        # Fourth bracket (gamma^5)
        bracket4 = (
            4 * np.exp(-gamma * eta) / gamma**5
            - 4 / gamma**5
            + eta * np.exp(-gamma * eta) / gamma**4
            + 3 * eta / gamma**4
            - eta**2 / gamma**3
            + eta**3 / (6 * gamma**2)
        )
        term7 = -(gamma**5) * bracket4

        val = term1 + term2 + term3 + term4 + term5 + term6 + term7

        return val

    def mu22(self):
        gamma = self.gamma
        eta = self.eta
        term1 = 1
        term2 = -(gamma**2) * eta**2 / 2
        term3 = gamma**4 * eta**4 / 24

        # Bracket 1
        bracket1 = (
            np.exp(-gamma * eta) / gamma**4
            - 1 / gamma**4
            + eta / gamma**3
            - eta**2 / (2 * gamma**2)
            + eta**3 / (6 * gamma)
        )
        term4 = gamma**4 * bracket1

        # Bracket 2
        bracket2 = np.exp(-gamma * eta) / gamma**2 - 1 / gamma**2 + eta / gamma
        term5 = -(gamma**2) * bracket2

        # Bracket 3 (coefficient γ⁴ / 2!)
        bracket3 = (
            2 * np.exp(-gamma * eta) / gamma**4
            - 2 / gamma**4
            + 2 * eta / gamma**3
            - eta**2 / gamma**2
            + eta**3 / (3 * gamma)
        )
        term6 = (gamma**4 / 2) * bracket3

        # Bracket 4
        bracket4 = (
            -3 * np.exp(-gamma * eta) / gamma**4
            + 3 / gamma**4
            - eta * np.exp(-gamma * eta) / gamma**3
            - 2 * eta / gamma**3
            + eta**2 / (2 * gamma**2)
        )
        term7 = gamma**4 * bracket4

        val = term1 + term2 + term3 + term4 + term5 + term6 + term7

        return val

    def mu23(self):
        gamma = self.gamma
        eta = self.eta
        # Term 1
        term1 = gamma**5 * eta**5 / 120

        # Bracket 1 (gamma^3)
        bracket1 = (
            -np.exp(-gamma * eta) / gamma**3
            + 1 / gamma**3
            - eta / gamma**2
            + eta**2 / (2 * gamma)
        )
        term2 = -(gamma**3) * bracket1

        # Bracket 2 (gamma^5)
        bracket2 = (
            -np.exp(-gamma * eta) / gamma**5
            + 1 / gamma**5
            - eta / gamma**4
            + eta**2 / (2 * gamma**3)
            - eta**3 / (6 * gamma**2)
            + eta**4 / (24 * gamma)
        )
        term3 = gamma**5 * bracket2

        # Term 4
        term4 = 1 - np.exp(-gamma * eta)

        # Bracket 3 (gamma^5 / 3!)
        bracket3 = (
            -6 * np.exp(-gamma * eta) / gamma**5
            + 6 / gamma**5
            - 6 * eta / gamma**4
            + 3 * eta**2 / gamma**3
            - eta**3 / gamma**2
            + eta**4 / (4 * gamma)
        )
        term5 = (gamma**5 / 6) * bracket3

        # Bracket 4 (gamma^5)
        bracket4 = (
            4 * np.exp(-gamma * eta) / gamma**5
            - 4 / gamma**5
            + eta * np.exp(-gamma * eta) / gamma**4
            + 3 * eta / gamma**4
            - eta**2 / gamma**3
            + eta**3 / (6 * gamma**2)
        )
        term6 = gamma**5 * bracket4

        val = term1 + term2 + term3 + term4 + term5 + term6

        return val

    def mu31(self):
        gamma = self.gamma
        eta = self.eta
        exp = np.exp(-gamma * eta)

        # Term 1
        bracket1 = exp / gamma**2 - 1 / gamma**2 + eta / gamma
        term1 = gamma**2 * bracket1

        # Term 2
        bracket2 = (
            6 * exp / gamma**4
            - 6 / gamma**4
            + 6 * eta / gamma**3
            - 3 * eta**2 / gamma**2
            + eta**3 / gamma
        )
        term2 = -(gamma**4 / 6) * bracket2

        # Term 3
        bracket3 = (
            120 * exp / gamma**6
            - 120 / gamma**6
            + 120 * eta / gamma**5
            - 60 * eta**2 / gamma**4
            + 20 * eta**3 / gamma**3
            - 5 * eta**4 / gamma**2
            + eta**5 / gamma
        )
        term3 = (gamma**6 / 120) * bracket3

        # Term 4
        bracket4 = (
            -5 * exp / gamma**6
            + 5 / gamma**6
            - eta * exp / gamma**5
            - 4 * eta / gamma**5
            + 3 * eta**2 / (2 * gamma**4)
            - eta**3 / (3 * gamma**3)
            + eta**4 / (24 * gamma**2)
        )
        term4 = gamma**6 * bracket4

        # Term 5
        bracket5 = (
            -3 * exp / gamma**4
            + 3 / gamma**4
            - eta * exp / gamma**3
            - 2 * eta / gamma**3
            + eta**2 / (2 * gamma**2)
        )
        term5 = -(gamma**4) * bracket5

        # Term 6
        bracket6 = (
            -30 * exp / gamma**6
            + 30 / gamma**6
            - 6 * eta * exp / gamma**5
            - 24 * eta / gamma**5
            + 9 * eta**2 / gamma**4
            - 2 * eta**3 / gamma**3
            + eta**4 / (4 * gamma**2)
        )
        term6 = (gamma**6 / 6) * bracket6

        # Term 7
        bracket7 = (
            10 * exp / gamma**6
            - 10 / gamma**6
            + 4 * eta * exp / gamma**5
            + 6 * eta / gamma**5
            + eta**2 * exp / (2 * gamma**4)
            - 3 * eta**2 / (2 * gamma**4)
            + eta**3 / (6 * gamma**3)
        )
        term7 = gamma**6 * bracket7

        val = term1 + term2 + term3 + term4 + term5 + term6 + term7

        return val

    def mu32(self):
        gamma = self.gamma
        eta = self.eta
        exp = np.exp(-gamma * eta)

        # Term 1
        bracket1 = 1 / gamma - exp / gamma
        term1 = -gamma * bracket1

        # Term 2
        bracket2 = (
            -2 * exp / gamma**3
            + 2 / gamma**3
            - 2 * eta / gamma**2
            + eta**2 / gamma
        )
        term2 = (gamma**3 / 2) * bracket2

        # Term 3
        bracket3 = (
            -24 * exp / gamma**5
            + 24 / gamma**5
            - 24 * eta / gamma**4
            + 12 * eta**2 / gamma**3
            - 4 * eta**3 / gamma**2
            + eta**4 / gamma
        )
        term3 = -(gamma**5 / 24) * bracket3

        # Term 4
        bracket4 = (
            4 * exp / gamma**5
            - 4 / gamma**5
            + eta * exp / gamma**4
            + 3 * eta / gamma**4
            - eta**2 / gamma**3
            + eta**3 / (6 * gamma**2)
        )
        term4 = -(gamma**5) * bracket4

        # Term 5
        bracket5 = (
            2 * exp / gamma**3
            - 2 / gamma**3
            + eta * exp / gamma**2
            + eta / gamma**2
        )
        term5 = gamma**3 * bracket5

        # Term 6
        bracket6 = (
            8 * exp / gamma**5
            - 8 / gamma**5
            + 2 * eta * exp / gamma**4
            + 6 * eta / gamma**4
            - 2 * eta**2 / gamma**3
            + eta**3 / (3 * gamma**2)
        )
        term6 = -(gamma**5 / 2) * bracket6

        # Term 7
        bracket7 = (
            -6 * exp / gamma**5
            + 6 / gamma**5
            - 3 * eta * exp / gamma**4
            - 3 * eta / gamma**4
            - eta**2 * exp / (2 * gamma**3)
            + eta**2 / (2 * gamma**3)
        )
        term7 = -(gamma**5) * bracket7

        val = term1 + term2 + term3 + term4 + term5 + term6 + term7

        return val

    def mu33(self):
        gamma = self.gamma
        eta = self.eta
        exp = np.exp(-gamma * eta)

        # Term 1
        term1 = exp

        # Term 2
        bracket2 = (
            120 * exp / gamma**6
            - 120 / gamma**6
            + 120 * eta / gamma**5
            - 60 * eta**2 / gamma**4
            + 20 * eta**3 / gamma**3
            - 5 * eta**4 / gamma**2
            + eta**5 / gamma
        )
        term2 = -(gamma**6 / 120) * bracket2

        # Term 3
        bracket3 = (
            -3 * exp / gamma**4
            + 3 / gamma**4
            - eta * exp / gamma**3
            - 2 * eta / gamma**3
            + eta**2 / (2 * gamma**2)
        )
        term3 = gamma**4 * bracket3

        # Term 4
        bracket4 = (
            -5 * exp / gamma**6
            + 5 / gamma**6
            - eta * exp / gamma**5
            - 4 * eta / gamma**5
            + 3 * eta**2 / (2 * gamma**4)
            - eta**3 / (3 * gamma**3)
            + eta**4 / (24 * gamma**2)
        )
        term4 = -(gamma**6) * bracket4

        # Term 5
        bracket5 = -exp / gamma**2 + 1 / gamma**2 - eta * exp / gamma
        term5 = -(gamma**2) * bracket5

        # Term 6
        bracket6 = (
            -30 * exp / gamma**6
            + 30 / gamma**6
            - 6 * eta * exp / gamma**5
            - 24 * eta / gamma**5
            + 9 * eta**2 / gamma**4
            - 2 * eta**3 / gamma**3
            + eta**4 / (4 * gamma**2)
        )
        term6 = -(gamma**6 / 6) * bracket6

        # Term 7
        bracket7 = (
            3 * exp / gamma**4
            - 3 / gamma**4
            + 2 * eta * exp / gamma**3
            + eta / gamma**3
            + eta**2 * exp / (2 * gamma**2)
        )
        term7 = gamma**4 * bracket7

        # Term 8
        bracket8 = (
            10 * exp / gamma**6
            - 10 / gamma**6
            + 4 * eta * exp / gamma**5
            + 6 * eta / gamma**5
            + eta**2 * exp / (2 * gamma**4)
            - 3 * eta**2 / (2 * gamma**4)
            + eta**3 / (6 * gamma**3)
        )
        term8 = -(gamma**6) * bracket8

        val = term1 + term2 + term3 + term4 + term5 + term6 + term7 + term8

        return val

    def sigma00(self):
        gamma = self.gamma
        eta = self.eta
        val = (
            ((2 * eta) / gamma)
            - (
                (np.exp(-2 * gamma * eta) - 4 * np.exp(-gamma * eta) + 3)
                / np.power(gamma, 2)
            )
            + ((4 * np.power(eta, 3) * gamma) / 3.0)
            + 2 * np.power(eta, 2) * np.exp(-eta * gamma)
            - 2 * np.power(eta, 2)
            - ((np.power(eta, 4) * np.power(gamma, 2)) / 2)
            + ((np.power(eta, 5) * np.power(gamma, 3)) / 10)
        )
        return val

    def sigma11(self):
        gamma = self.gamma
        eta = self.eta
        val = (
            (2 * eta * gamma)
            - np.exp(-2 * eta * gamma)
            - (2 * np.power(eta, 2) * np.power(gamma, 2))
            + ((2 * np.power(eta, 3) * np.power(gamma, 3)) / 3)
            - (4 * eta * gamma * np.exp(-eta * gamma))
            + 1
        )
        return val

    def sigma22(self):
        gamma = self.gamma
        eta = self.eta
        val = (
            (4 * np.exp(-eta * gamma))
            - ((13 * np.exp(-2 * eta * gamma)) / 2)
            + (8 * eta * gamma)
            - ((4 * np.power(eta, 3) * np.power(gamma, 3)) / 3)
            + ((np.power(eta, 5) * np.power(gamma, 5)) / 10)
            - (
                10
                * (np.power(eta, 2) * np.power(gamma, 2))
                * np.exp(-eta * gamma)
            )
            - (np.power(eta, 2) * np.power(gamma, 2)
                * np.exp(-2 * eta * gamma))
            - (
                2
                * (np.power(eta, 3) * np.power(gamma, 3))
                * np.exp(-eta * gamma)
            )
            - 12 * eta * gamma * np.exp(-eta * gamma)
            - 5 * eta * gamma * np.exp(-2 * eta * gamma)
            + 2.5
        )
        return val

    def sigma33(self):
        gamma = self.gamma
        eta = self.eta
        val = (
            (283 * eta) / 4
            + 88 * np.exp(-eta * gamma)
            - (397 * np.exp(-2 * eta * gamma)) / 8
            + 32 * eta * gamma
            + 84 * eta * np.exp(-eta * gamma)
            - (101 * eta * np.exp(-2 * eta * gamma)) / 4
            + (159 * eta) / (2 * gamma)
            - 24 * eta**2 * gamma
            + 6 * eta**3 * gamma
            + 32 * eta**2 * np.exp(-eta * gamma)
            - (eta**2 * np.exp(-2 * eta * gamma)) / 2
            + (204 * np.exp(-eta * gamma)) / gamma
            - (149 * np.exp(-2 * eta * gamma)) / (4 * gamma)
            + (192 * np.exp(-eta * gamma)) / gamma**2
            - (21 * np.exp(-2 * eta * gamma)) / (2 * gamma**2)
            - (39 * eta**2) / 2
            - 667 / (4 * gamma)
            - 363 / (2 * gamma**2)
            - 8 * eta**2 * gamma**2
            + (22 * eta**3 * gamma**2) / 3
            + (2 * eta**3 * gamma**3) / 3
            - 2 * eta**4 * gamma**2
            - (4 * eta**4 * gamma**3) / 3
            + (7 * eta**5 * gamma**3) / 15
            + (eta**5 * gamma**4) / 10
            - (eta**6 * gamma**4) / 15
            + (eta**7 * gamma**5) / 210
            + (96 * eta * np.exp(-eta * gamma)) / gamma
            - (9 * eta * np.exp(-2 * eta * gamma)) / (2 * gamma)
            + 36 * eta**2 * gamma * np.exp(-eta * gamma)
            - 6 * eta**2 * gamma * np.exp(-2 * eta * gamma)
            + 4 * eta**3 * gamma * np.exp(-eta * gamma)
            - 10 * eta**2 * gamma**2 * np.exp(-eta * gamma)
            - (77 * eta**2 * gamma**2 * np.exp(-2 * eta * gamma)) / 4
            + 10 * eta**3 * gamma**2 * np.exp(-eta * gamma)
            - (eta**3 * gamma**2 * np.exp(-2 * eta * gamma)) / 2
            - 2 * eta**3 * gamma**3 * np.exp(-eta * gamma)
            - (7 * eta**3 * gamma**3 * np.exp(-2 * eta * gamma)) / 2
            + eta**4 * gamma**3 * np.exp(-eta * gamma)
            - (eta**4 * gamma**4 * np.exp(-2 * eta * gamma)) / 4
            + 8 * eta * gamma * np.exp(-eta * gamma)
            - (197 * eta * gamma * np.exp(-2 * eta * gamma)) / 4
            - 307 / 8
        )
        return val

    def sigma01(self):
        gamma = self.gamma
        eta = self.eta
        exp1 = np.exp(eta * gamma)
        exp2 = np.exp(-2 * eta * gamma)
        inner = (
            2 * exp1 + eta**2 * gamma**2 * exp1
            - 2 * eta * gamma * exp1 - 2
        )
        val = (exp2 * inner**2) / (4 * gamma)
        return val

    def sigma02(self):
        gamma = self.gamma
        eta = self.eta

        exp1 = np.exp(-eta * gamma)
        exp2 = np.exp(-2 * eta * gamma)

        val = (
            4 * eta
            + 2 * eta * exp1
            - eta * exp2
            - 2 * eta**2 * gamma
            + (10 * exp1) / gamma
            - (5 * exp2) / (2 * gamma)
            - (15) / (2 * gamma)
            + (eta**3 * gamma**2) / 3
            + (eta**4 * gamma**3) / 4
            - (eta**5 * gamma**4) / 10
            + 2 * eta**2 * gamma * exp1
            + eta**3 * gamma**2 * exp1
        )
        return val

    def sigma03(self):
        gamma = self.gamma
        eta = self.eta
        exp1 = np.exp(-eta * gamma)
        exp2 = np.exp(-2 * eta * gamma)

        val = (
            (7 * eta * exp2) / 2
            - 18 * eta * exp1
            - 8 * eta
            - (21 * eta) / (2 * gamma)
            + 5 * eta**2 * gamma
            - (5 * eta**3 * gamma) / 3
            - 8 * eta**2 * exp1
            - (36 * exp1) / gamma
            + (27 * exp2) / (4 * gamma)
            - (32 * exp1) / gamma**2
            + (2 * exp2) / gamma**2
            + 3 * eta**2
            + 117 / (4 * gamma)
            + 30 / gamma**2
            - 2 * eta**3 * gamma**2
            + (2 * eta**4 * gamma**2) / 3
            + (eta**4 * gamma**3) / 4
            - (3 * eta**5 * gamma**3) / 20
            + (eta**6 * gamma**4) / 60
            - (18 * eta * exp1) / gamma
            + (eta * exp2) / (2 * gamma)
            - 12 * eta**2 * gamma * exp1
            + (eta**2 * gamma * exp2) / 2
            - eta**3 * gamma * exp1
            - 4 * eta**3 * gamma**2 * exp1
            - (eta**4 * gamma**3 * exp1) / 2
        )
        return val

    def sigma12(self):
        gamma = self.gamma
        eta = self.eta
        exp1 = np.exp(-eta * gamma)
        exp2 = np.exp(-2 * eta * gamma)

        val = (
            (5 * exp2) / 2
            - 4 * eta * gamma
            + 2 * eta**2 * gamma**2
            + (eta**3 * gamma**3) / 3
            - (eta**4 * gamma**4) / 4
            + 3 * eta**2 * gamma**2 * exp1
            + 8 * eta * gamma * exp1
            + eta * gamma * exp2
            - 5 / 2
        )
        return val

    def sigma13(self):
        gamma = self.gamma
        eta = self.eta

        exp1 = np.exp(-eta * gamma)
        exp2 = np.exp(-2 * eta * gamma)

        val = (
            8 * eta * gamma
            - 4 * exp1
            - (27 * exp2) / 4
            - (3 * eta) / 2
            - 12 * eta * exp1
            - (eta * exp2) / 2
            - 3 * eta**2 * gamma
            - (10 * exp1) / gamma
            - (2 * exp2) / gamma
            + 12 / gamma
            - 5 * eta**2 * gamma**2
            + (5 * eta**3 * gamma**2) / 3
            + (2 * eta**3 * gamma**3) / 3
            - (5 * eta**4 * gamma**3) / 12
            + (eta**5 * gamma**4) / 20
            - eta**2 * gamma * exp1
            - 8 * eta**2 * gamma**2 * exp1
            - (eta**2 * gamma**2 * exp2) / 2
            - eta**3 * gamma**3 * exp1
            - 22 * eta * gamma * exp1
            - (7 * eta * gamma * exp2) / 2
            + 43 / 4
        )
        return val

    def sigma23(self):
        gamma = self.gamma
        eta = self.eta
        exp1 = np.exp(-eta * gamma)
        exp2 = np.exp(-2 * eta * gamma)

        val = (
            (143 * exp2) / 8
            - 12 * exp1
            - 7 * eta
            - 16 * eta * gamma
            + 18 * eta * exp1
            + (7 * eta * exp2) / 2
            + 6 * eta**2 * gamma
            + (2 * exp1) / gamma
            + (25 * exp2) / (4 * gamma)
            - 33 / (4 * gamma)
            + 2 * eta**2 * gamma**2
            - (4 * eta**3 * gamma**2) / 3
            + (4 * eta**3 * gamma**3) / 3
            - (eta**4 * gamma**3) / 12
            - (eta**4 * gamma**4) / 4
            + (eta**5 * gamma**4) / 10
            - (eta**6 * gamma**5) / 60
            + 5 * eta**2 * gamma * exp1
            + (eta**2 * gamma * exp2) / 2
            + 20 * eta**2 * gamma**2 * exp1
            + (19 * eta**2 * gamma**2 * exp2) / 4
            + 5 * eta**3 * gamma**3 * exp1
            + (eta**3 * gamma**3 * exp2) / 2
            + (eta**4 * gamma**4 * exp1) / 2
            + 24 * eta * gamma * exp1
            + (63 * eta * gamma * exp2) / 4
            - 47 / 8
        )
        return val

    def sigma(self, d):
        s00 = self.sigma00()
        s01 = self.sigma01()
        s02 = self.sigma02()
        s03 = self.sigma03()
        s11 = self.sigma11()
        s12 = self.sigma12()
        s13 = self.sigma13()
        s22 = self.sigma22()
        s23 = self.sigma23()
        s33 = self.sigma33()

        I_d = np.eye(d)

        top_mat = np.hstack([s00 * I_d, s01 * I_d, s02 * I_d, s03 * I_d])
        mid_mat1 = np.hstack([s01 * I_d, s11 * I_d, s12 * I_d, s13 * I_d])
        mid_mat2 = np.hstack([s02 * I_d, s12 * I_d, s22 * I_d, s23 * I_d])
        bot_mat = np.hstack([s03 * I_d, s13 * I_d, s23 * I_d, s33 * I_d])

        mat = np.vstack([top_mat, mid_mat1, mid_mat2, bot_mat])
        epsilon = 0.00001
        matrix = mat + epsilon * np.eye(4 * d)

        return matrix

Base class for performing grid search over Langevin Monte Carlo hyperparameters.

Parameters

gammas : list List of gamma (friction) values to try. etas : list List of eta (step size) values to try. xis : list List of xi values (used only for third-order methods). If None, fourth-order is assumed. N : int Number of MCMC samples to draw for each parameter configuration. Required. seed : int Random seed for reproducibility. show_progress : bool, default=True Whether to show a progress bar during the grid search.

Source code in holmc/utils/gridsearch.py
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
class GridSearch:
    """
    Base class for performing grid search over Langevin Monte Carlo
    hyperparameters.

    Parameters
    ----------
    gammas : list
        List of gamma (friction) values to try.
    etas : list
        List of eta (step size) values to try.
    xis : list
        List of xi values (used only for third-order methods). If None,
        fourth-order is assumed.
    N : int
        Number of MCMC samples to draw for each parameter configuration.
        Required.
    seed : int
        Random seed for reproducibility.
    show_progress : bool, default=True
        Whether to show a progress bar during the grid search.
    """

    def __init__(
        self,
        gammas: list = None,
        etas: list = None,
        xis: list = None,
        N: int = None,
        seed: int = None,
        show_progress: bool = True,
    ):
        self.gammas = gammas
        self.etas = etas
        self.xis = xis
        self.N = N
        self.seed = seed
        self.show_progress = show_progress
        if seed is not None:
            np.random.seed(seed)
        if N is None:
            raise ValueError("N must be specified for grid search.")

Bases: GridSearch

Grid search implementation for Bayesian linear regression using HoLMC samplers.

This class runs over a grid of (eta, gamma, xi) parameters and evaluates performance using the Wasserstein-2 distance between the sampled distribution and the target posterior.

Methods

run(X, y, lamb): Executes the grid search and returns a DataFrame of results sorted by W2 distance.

Source code in holmc/utils/gridsearch.py
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
class GridSearchRegression(GridSearch):
    """
    Grid search implementation for Bayesian linear regression using HoLMC
    samplers.

    This class runs over a grid of (eta, gamma, xi) parameters and evaluates
    performance
    using the Wasserstein-2 distance between the sampled distribution and the
    target posterior.

    Methods
    -------
    run(X, y, lamb):
        Executes the grid search and returns a DataFrame of results sorted by
        W2 distance.
    """

    def run(self, X: np.ndarray, y: np.ndarray, lamb: float = None):
        """
        Run the grid search for regression.

        Parameters
        ----------
        X : np.ndarray
            Design matrix of shape (n_samples, n_features).
        y : np.ndarray
            Response vector of shape (n_samples,) or (n_samples, 1).
        lamb : float
            Regularization (prior precision) parameter. Required.

        Returns
        -------
        pd.DataFrame
            DataFrame containing the grid search results sorted by minimum
            Wasserstein-2 distance.
        """
        if lamb is None:
            raise ValueError("lamb must be specified for grid search.")

        if X is None or y is None:
            raise ValueError("X and y must be provided for grid search.")

        N = self.N

        results = []

        is_third_order = self.xis is not None

        for eta in tqdm(self.etas, disable=not self.show_progress, desc="Eta"):
            for gamma in self.gammas:
                xi_list = self.xis if is_third_order else [None]
                for xi in xi_list:
                    try:
                        if is_third_order:
                            params = O3Params(eta=eta, gamma=gamma, xi=xi)
                            sampler = HoLMCSamplerO3Regression(
                                params=params,
                                N=N,
                                seed=self.seed,
                                show_progress=False,
                            )
                        else:
                            params = O4Params(eta=eta, gamma=gamma)
                            sampler = HoLMCSamplerO4Regression(
                                params=params,
                                N=N,
                                seed=self.seed,
                                show_progress=False,
                            )
                        samples = sampler.sample(X, y, lamb)
                        metric = Wasserstein2Distance(X=X, y=y)
                        dist = metric.w2distance(samples)
                        min_dist = np.nanmin(dist)

                        result = {
                            "gamma": gamma,
                            "eta": eta,
                            "w2dist": min_dist,
                        }
                        if is_third_order:
                            result["xi"] = xi
                        results.append(result)
                    except Exception:
                        result = {"gamma": gamma, "eta": eta, "w2dist": np.nan}
                        if is_third_order:
                            result["xi"] = xi
                        results.append(result)

        self.results_df = pd.DataFrame(results).sort_values("w2dist")
        return self.results_df

run(X, y, lamb=None)

Run the grid search for regression.

Parameters

X : np.ndarray Design matrix of shape (n_samples, n_features). y : np.ndarray Response vector of shape (n_samples,) or (n_samples, 1). lamb : float Regularization (prior precision) parameter. Required.

Returns

pd.DataFrame DataFrame containing the grid search results sorted by minimum Wasserstein-2 distance.

Source code in holmc/utils/gridsearch.py
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
def run(self, X: np.ndarray, y: np.ndarray, lamb: float = None):
    """
    Run the grid search for regression.

    Parameters
    ----------
    X : np.ndarray
        Design matrix of shape (n_samples, n_features).
    y : np.ndarray
        Response vector of shape (n_samples,) or (n_samples, 1).
    lamb : float
        Regularization (prior precision) parameter. Required.

    Returns
    -------
    pd.DataFrame
        DataFrame containing the grid search results sorted by minimum
        Wasserstein-2 distance.
    """
    if lamb is None:
        raise ValueError("lamb must be specified for grid search.")

    if X is None or y is None:
        raise ValueError("X and y must be provided for grid search.")

    N = self.N

    results = []

    is_third_order = self.xis is not None

    for eta in tqdm(self.etas, disable=not self.show_progress, desc="Eta"):
        for gamma in self.gammas:
            xi_list = self.xis if is_third_order else [None]
            for xi in xi_list:
                try:
                    if is_third_order:
                        params = O3Params(eta=eta, gamma=gamma, xi=xi)
                        sampler = HoLMCSamplerO3Regression(
                            params=params,
                            N=N,
                            seed=self.seed,
                            show_progress=False,
                        )
                    else:
                        params = O4Params(eta=eta, gamma=gamma)
                        sampler = HoLMCSamplerO4Regression(
                            params=params,
                            N=N,
                            seed=self.seed,
                            show_progress=False,
                        )
                    samples = sampler.sample(X, y, lamb)
                    metric = Wasserstein2Distance(X=X, y=y)
                    dist = metric.w2distance(samples)
                    min_dist = np.nanmin(dist)

                    result = {
                        "gamma": gamma,
                        "eta": eta,
                        "w2dist": min_dist,
                    }
                    if is_third_order:
                        result["xi"] = xi
                    results.append(result)
                except Exception:
                    result = {"gamma": gamma, "eta": eta, "w2dist": np.nan}
                    if is_third_order:
                        result["xi"] = xi
                    results.append(result)

    self.results_df = pd.DataFrame(results).sort_values("w2dist")
    return self.results_df

Bases: GridSearch

Grid search implementation for Bayesian logistic regression using HoLMC samplers.

This class evaluates sampler performance over a grid of parameters using predictive accuracy based on samples averaged over time.

Methods

run(X, y, lamb): Executes the grid search and returns a DataFrame sorted by maximum accuracy. compute_accuracy(X, y, samples): Computes predictive accuracy from the sample sequence.

Source code in holmc/utils/gridsearch.py
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
class GridSearchClassification(GridSearch):
    """
    Grid search implementation for Bayesian logistic regression using HoLMC
    samplers.

    This class evaluates sampler performance over a grid of parameters using
    predictive accuracy
    based on samples averaged over time.

    Methods
    -------
    run(X, y, lamb):
        Executes the grid search and returns a DataFrame sorted by maximum
        accuracy.
    compute_accuracy(X, y, samples):
        Computes predictive accuracy from the sample sequence.
    """

    def compute_accuracy(self, X, y, samples):
        """
        Compute classification accuracy over cumulative average of sampled
        parameters.

        Parameters
        ----------
        X : np.ndarray
            Feature matrix of shape (n_samples, n_features).
        y : np.ndarray
            Binary target labels (0 or 1) of shape (n_samples,).
        samples : np.ndarray
            Array of sampled parameter vectors of shape (n_samples, n_features)

        Returns
        -------
        np.ndarray
            Array of accuracy scores as function of the sample index.
        """
        n = samples.shape[0]
        accuracies = []

        for i in range(1, n + 1):
            avg_theta = np.mean(samples[:i], axis=0)
            logits = X @ avg_theta
            probs = sigmoid(logits)
            y_pred = (probs >= 0.5).astype(int)
            acc = accuracy(y, y_pred)
            accuracies.append(acc)

        return np.array(accuracies)

    def run(self, X: np.ndarray, y: np.ndarray, lamb: float = None):
        """
        Run the grid search for classification.

        Parameters
        ----------
        X : np.ndarray
            Feature matrix of shape (n_samples, n_features).
        y : np.ndarray
            Binary target labels (0 or 1) of shape (n_samples,).
        lamb : float
            Regularization (prior precision) parameter. Required.

        Returns
        -------
        pd.DataFrame
            DataFrame containing the grid search results sorted by maximum
            accuracy.
        """
        if lamb is None:
            raise ValueError("lamb must be specified for grid search.")

        results = []
        N = self.N

        is_third_order = self.xis is not None

        for eta in tqdm(self.etas, disable=not self.show_progress, desc="Eta"):
            for gamma in self.gammas:
                xi_list = self.xis if is_third_order else [None]
                for xi in xi_list:
                    try:
                        if is_third_order:
                            params = O3Params(eta=eta, gamma=gamma, xi=xi)
                            sampler = HoLMCSamplerO3Classification(
                                params=params,
                                N=N,
                                seed=self.seed,
                                show_progress=False,
                            )
                        else:
                            params = O4Params(eta=eta, gamma=gamma)
                            sampler = HoLMCSamplerO4Classification(
                                params=params,
                                N=N,
                                seed=self.seed,
                                show_progress=False,
                            )
                        samples = sampler.sample(X, y, lamb)
                        ac = self.compute_accuracy(X, y, samples)
                        max_acc = np.nanmax(ac)

                        result = {
                            "gamma": gamma,
                            "eta": eta,
                            "MaxAcc": max_acc,
                        }
                        if is_third_order:
                            result["xi"] = xi
                        results.append(result)
                    except Exception:
                        result = {"gamma": gamma, "eta": eta, "MaxAcc": np.nan}
                        if is_third_order:
                            result["xi"] = xi
                        results.append(result)

        self.results_df = pd.DataFrame(results).sort_values(
            "MaxAcc", ascending=False
        )
        return self.results_df

compute_accuracy(X, y, samples)

Compute classification accuracy over cumulative average of sampled parameters.

Parameters

X : np.ndarray Feature matrix of shape (n_samples, n_features). y : np.ndarray Binary target labels (0 or 1) of shape (n_samples,). samples : np.ndarray Array of sampled parameter vectors of shape (n_samples, n_features)

Returns

np.ndarray Array of accuracy scores as function of the sample index.

Source code in holmc/utils/gridsearch.py
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
def compute_accuracy(self, X, y, samples):
    """
    Compute classification accuracy over cumulative average of sampled
    parameters.

    Parameters
    ----------
    X : np.ndarray
        Feature matrix of shape (n_samples, n_features).
    y : np.ndarray
        Binary target labels (0 or 1) of shape (n_samples,).
    samples : np.ndarray
        Array of sampled parameter vectors of shape (n_samples, n_features)

    Returns
    -------
    np.ndarray
        Array of accuracy scores as function of the sample index.
    """
    n = samples.shape[0]
    accuracies = []

    for i in range(1, n + 1):
        avg_theta = np.mean(samples[:i], axis=0)
        logits = X @ avg_theta
        probs = sigmoid(logits)
        y_pred = (probs >= 0.5).astype(int)
        acc = accuracy(y, y_pred)
        accuracies.append(acc)

    return np.array(accuracies)

run(X, y, lamb=None)

Run the grid search for classification.

Parameters

X : np.ndarray Feature matrix of shape (n_samples, n_features). y : np.ndarray Binary target labels (0 or 1) of shape (n_samples,). lamb : float Regularization (prior precision) parameter. Required.

Returns

pd.DataFrame DataFrame containing the grid search results sorted by maximum accuracy.

Source code in holmc/utils/gridsearch.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def run(self, X: np.ndarray, y: np.ndarray, lamb: float = None):
    """
    Run the grid search for classification.

    Parameters
    ----------
    X : np.ndarray
        Feature matrix of shape (n_samples, n_features).
    y : np.ndarray
        Binary target labels (0 or 1) of shape (n_samples,).
    lamb : float
        Regularization (prior precision) parameter. Required.

    Returns
    -------
    pd.DataFrame
        DataFrame containing the grid search results sorted by maximum
        accuracy.
    """
    if lamb is None:
        raise ValueError("lamb must be specified for grid search.")

    results = []
    N = self.N

    is_third_order = self.xis is not None

    for eta in tqdm(self.etas, disable=not self.show_progress, desc="Eta"):
        for gamma in self.gammas:
            xi_list = self.xis if is_third_order else [None]
            for xi in xi_list:
                try:
                    if is_third_order:
                        params = O3Params(eta=eta, gamma=gamma, xi=xi)
                        sampler = HoLMCSamplerO3Classification(
                            params=params,
                            N=N,
                            seed=self.seed,
                            show_progress=False,
                        )
                    else:
                        params = O4Params(eta=eta, gamma=gamma)
                        sampler = HoLMCSamplerO4Classification(
                            params=params,
                            N=N,
                            seed=self.seed,
                            show_progress=False,
                        )
                    samples = sampler.sample(X, y, lamb)
                    ac = self.compute_accuracy(X, y, samples)
                    max_acc = np.nanmax(ac)

                    result = {
                        "gamma": gamma,
                        "eta": eta,
                        "MaxAcc": max_acc,
                    }
                    if is_third_order:
                        result["xi"] = xi
                    results.append(result)
                except Exception:
                    result = {"gamma": gamma, "eta": eta, "MaxAcc": np.nan}
                    if is_third_order:
                        result["xi"] = xi
                    results.append(result)

    self.results_df = pd.DataFrame(results).sort_values(
        "MaxAcc", ascending=False
    )
    return self.results_df