GroupMultiNeSS 0.0.7__tar.gz → 0.0.8__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS/group_multiness.py +304 -100
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS/multiness.py +760 -66
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS.egg-info/PKG-INFO +43 -28
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/PKG-INFO +43 -28
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/README.md +42 -27
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/setup.py +1 -1
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS/MASE.py +0 -0
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS/__init__.py +0 -0
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS/base.py +0 -0
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS/data_generation.py +0 -0
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS/shared_space_hunting.py +0 -0
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS/utils.py +0 -0
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS.egg-info/SOURCES.txt +0 -0
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS.egg-info/dependency_links.txt +0 -0
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS.egg-info/requires.txt +0 -0
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/GroupMultiNeSS.egg-info/top_level.txt +0 -0
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/LICENSE +0 -0
- {groupmultiness-0.0.7 → groupmultiness-0.0.8}/setup.cfg +0 -0
|
@@ -1,16 +1,14 @@
|
|
|
1
1
|
import numpy as np
|
|
2
2
|
from typing import List, Optional, Union
|
|
3
|
-
from copy import deepcopy
|
|
4
3
|
from collections import Counter
|
|
5
4
|
from functools import partial
|
|
6
5
|
from joblib import Parallel, delayed
|
|
7
6
|
from warnings import warn
|
|
8
|
-
from contextlib import ExitStack, closing
|
|
9
7
|
|
|
10
8
|
from .multiness import BaseMultiNeSS, BaseMultiNeSSRefined, BaseMultiNeSSRefinedCV, BaseOracleMultiNeSS
|
|
11
9
|
from .base import BaseRefitting
|
|
12
10
|
from .utils import if_scalar_or_given_length_array, fill_diagonals, \
|
|
13
|
-
soft_thresholding_operator, hard_thresholding_operator
|
|
11
|
+
soft_thresholding_operator, hard_thresholding_operator
|
|
14
12
|
|
|
15
13
|
|
|
16
14
|
class BaseGroupMultiNeSS(BaseMultiNeSS):
|
|
@@ -32,8 +30,16 @@ class BaseGroupMultiNeSS(BaseMultiNeSS):
|
|
|
32
30
|
def __init__(self, group_indices: List[int],
|
|
33
31
|
edge_distrib: str = "normal",
|
|
34
32
|
loops_allowed: bool = True):
|
|
35
|
-
"""
|
|
36
|
-
|
|
33
|
+
"""Initialize BaseGroupMultiNeSS without fitting parameter matrices.
|
|
34
|
+
|
|
35
|
+
Parameters
|
|
36
|
+
----------
|
|
37
|
+
group_indices : list of int
|
|
38
|
+
Zero-based group assignment for each input layer; labels must span 0..K-1.
|
|
39
|
+
edge_distrib : str, optional
|
|
40
|
+
Edge distribution: 'normal', 'bernoulli', or 'poisson'.
|
|
41
|
+
loops_allowed : bool, optional
|
|
42
|
+
Whether diagonal entries contribute to fitting and expected adjacency.
|
|
37
43
|
"""
|
|
38
44
|
super().__init__(edge_distrib=edge_distrib, loops_allowed=loops_allowed)
|
|
39
45
|
self.group_indices = np.asarray(group_indices, dtype=int)
|
|
@@ -166,8 +172,24 @@ class BaseGroupMultiNeSSRefined(BaseGroupMultiNeSS, BaseMultiNeSSRefined):
|
|
|
166
172
|
sigmas: Optional[Union[float, List, np.ndarray]] = None,
|
|
167
173
|
loops_allowed: bool = True,
|
|
168
174
|
n_jobs: Optional[int] = None):
|
|
169
|
-
"""
|
|
170
|
-
|
|
175
|
+
"""Initialize BaseGroupMultiNeSSRefined without fitting parameter matrices.
|
|
176
|
+
|
|
177
|
+
Parameters
|
|
178
|
+
----------
|
|
179
|
+
group_indices : list of int
|
|
180
|
+
Zero-based group assignment for each input layer; labels must span 0..K-1.
|
|
181
|
+
edge_distrib : str, optional
|
|
182
|
+
Edge distribution: 'normal', 'bernoulli', or 'poisson'.
|
|
183
|
+
max_rank : int or None, optional
|
|
184
|
+
Maximum fitted component rank; None uses floor(sqrt(n_nodes)).
|
|
185
|
+
init_rank : int or None, optional
|
|
186
|
+
Initialization rank; None leaves averages untruncated.
|
|
187
|
+
sigmas : float or array-like or None, optional
|
|
188
|
+
Positive Gaussian noise standard deviations, broadcastable over layers and edges.
|
|
189
|
+
loops_allowed : bool, optional
|
|
190
|
+
Whether diagonal entries contribute to fitting and expected adjacency.
|
|
191
|
+
n_jobs : int or None, optional
|
|
192
|
+
Number of joblib threads for independent group descents.
|
|
171
193
|
"""
|
|
172
194
|
BaseMultiNeSSRefined.__init__(self, edge_distrib=edge_distrib, loops_allowed=loops_allowed,
|
|
173
195
|
max_rank=max_rank, init_rank=init_rank, sigmas=sigmas)
|
|
@@ -218,15 +240,28 @@ class BaseGroupMultiNeSSRefined(BaseGroupMultiNeSS, BaseMultiNeSSRefined):
|
|
|
218
240
|
*np.eye(self.n_layers_, dtype=bool)])
|
|
219
241
|
|
|
220
242
|
def _make_key_2_history_key_dict(self):
|
|
243
|
+
"""Map optimization keys to shared and group history labels.
|
|
244
|
+
"""
|
|
221
245
|
self._key_2_history_key = {0: 'Shared component', **{group + 1: f'GroupOptimize({group + 1})'
|
|
222
246
|
for group in self.unique_groups_}}
|
|
223
247
|
|
|
224
248
|
def _make_key_2_param_indices_dict(self):
|
|
249
|
+
"""Map each descent to its ordered matrix updates.
|
|
250
|
+
"""
|
|
225
251
|
self._key_2_param_indices = {0: [0], **{group + 1: self._get_group_dependent_matrix_indices(group)
|
|
226
252
|
for group in self.unique_groups_}}
|
|
227
253
|
|
|
228
254
|
def _optimized_params_init(self, As, key=0):
|
|
229
|
-
"""Equation (13): truncate the group average before subtracting S.
|
|
255
|
+
"""Equation (13): truncate the group average before subtracting S.
|
|
256
|
+
|
|
257
|
+
Parameters
|
|
258
|
+
----------
|
|
259
|
+
As : np.ndarray
|
|
260
|
+
Observed adjacency tensor with shape (n_layers, n_nodes, n_nodes);
|
|
261
|
+
NaN entries are excluded from the likelihood.
|
|
262
|
+
key : int
|
|
263
|
+
Optimization key: 0 for S, or 1..K for a group descent.
|
|
264
|
+
"""
|
|
230
265
|
As = self._initialization_data(As)
|
|
231
266
|
shared = hard_thresholding_operator(np.nansum(As, axis=0) / self.n_layers_,
|
|
232
267
|
max_rank=self.init_rank)
|
|
@@ -242,32 +277,61 @@ class BaseGroupMultiNeSSRefined(BaseGroupMultiNeSS, BaseMultiNeSSRefined):
|
|
|
242
277
|
self._set_matrix(hard_thresholding_operator(residual, max_rank=self.init_rank),
|
|
243
278
|
self.n_groups_ + layer + 1)
|
|
244
279
|
|
|
245
|
-
def _run_optimization(self, As, lr=None, n_outer_iter=
|
|
246
|
-
"""Algorithm 1: independent group descents, then one shared update.
|
|
280
|
+
def _run_optimization(self, As, lr=None, n_outer_iter=20, **optim_kwargs):
|
|
281
|
+
"""Algorithm 1: independent group descents, then one shared update.
|
|
282
|
+
|
|
283
|
+
Parameters
|
|
284
|
+
----------
|
|
285
|
+
As : np.ndarray
|
|
286
|
+
Observed adjacency tensor with shape (n_layers, n_nodes, n_nodes);
|
|
287
|
+
NaN entries are excluded from the likelihood.
|
|
288
|
+
lr : float or None, optional
|
|
289
|
+
Common step multiplier, divided by each matrix's layer participation count.
|
|
290
|
+
None uses 1 for Gaussian/Poisson and 3 for Bernoulli.
|
|
291
|
+
n_outer_iter : int, optional
|
|
292
|
+
Number of outer iterations to allocate or run; each contains group
|
|
293
|
+
descents followed by one shared update in GroupMultiNeSS.
|
|
294
|
+
**optim_kwargs : dict
|
|
295
|
+
Learning rate, stopping, verbosity, and history options forwarded to optimization.
|
|
296
|
+
"""
|
|
247
297
|
lr = self._learning_rate(lr)
|
|
248
298
|
stable_iterations = 0
|
|
249
299
|
for outer_iter in range(n_outer_iter):
|
|
250
|
-
previous = self.get_shared_latent_space().copy()
|
|
251
300
|
# Threads share parameter storage and histories; groups write disjoint
|
|
252
301
|
# matrices and S stays fixed until all group descents have finished.
|
|
253
302
|
Parallel(n_jobs=self.n_jobs, require='sharedmem')(
|
|
254
303
|
delayed(self._optimize_params)(key=group + 1, As=As, lr=lr,
|
|
255
304
|
outer_iter=outer_iter, **optim_kwargs)
|
|
256
305
|
for group in self.unique_groups_)
|
|
257
|
-
self._optimization_step([0], key=0, As=As, lr=lr, iteration=0,
|
|
306
|
+
change = self._optimization_step([0], key=0, As=As, lr=lr, iteration=0,
|
|
258
307
|
outer_iter=outer_iter, tol=optim_kwargs['tol'],
|
|
259
308
|
verbose=optim_kwargs.get('verbose', False) and
|
|
260
309
|
outer_iter % optim_kwargs.get('verbose_interval', 1) == 0,
|
|
261
310
|
save_latent_history=optim_kwargs.get('save_latent_history', False),
|
|
262
|
-
save_nll_history=optim_kwargs.get('save_nll_history', True)
|
|
263
|
-
|
|
264
|
-
self.convergence_history_[outer_iter][0].append(change)
|
|
311
|
+
save_nll_history=optim_kwargs.get('save_nll_history', True),
|
|
312
|
+
save_convergence_history=optim_kwargs.get('save_convergence_history', True))
|
|
265
313
|
stable_iterations = stable_iterations + 1 if change <= optim_kwargs['tol'] else 0
|
|
266
314
|
self.n_outer_iter_ = outer_iter + 1
|
|
267
315
|
if stable_iterations >= optim_kwargs['patience']:
|
|
268
316
|
break
|
|
269
317
|
|
|
270
318
|
def _error_components(self, key, true_params, estimates):
|
|
319
|
+
"""Select the ground-truth and estimated components for one history panel.
|
|
320
|
+
|
|
321
|
+
Parameters
|
|
322
|
+
----------
|
|
323
|
+
key : int
|
|
324
|
+
Optimization key: 0 for S, or 1..K for a group descent.
|
|
325
|
+
true_params : tuple of np.ndarray
|
|
326
|
+
Ground-truth matrices by component type: shared, optionally group, then individual.
|
|
327
|
+
estimates : list of np.ndarray
|
|
328
|
+
Estimated matrices grouped by component type.
|
|
329
|
+
|
|
330
|
+
Returns
|
|
331
|
+
-------
|
|
332
|
+
iterable of tuple
|
|
333
|
+
Plot label, reference matrix, and estimated matrix for each relevant component.
|
|
334
|
+
"""
|
|
271
335
|
if key == 0:
|
|
272
336
|
return [(r'$S$', true_params[0], estimates[0])]
|
|
273
337
|
group = key - 1
|
|
@@ -280,7 +344,8 @@ class GroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseRefitting):
|
|
|
280
344
|
"""GroupMultiNeSS with direct nuclear-norm penalties.
|
|
281
345
|
|
|
282
346
|
rho_0 penalizes S, rho_k penalizes each Q_k, and rho_kl penalizes each R_kl.
|
|
283
|
-
None defaults are
|
|
347
|
+
None defaults are c_rho*sqrt(M*n), c_rho*sqrt(m_k*n), and c_rho*sqrt(n),
|
|
348
|
+
respectively, with c_rho=3. Explicit penalties override their scaled defaults.
|
|
284
349
|
rho_k and rho_kl accept scalars or sequences in group and input-layer order.
|
|
285
350
|
Group labels remain 0..K-1; optimization/history keys are 0 for S and 1..K
|
|
286
351
|
for group descents. init_rank=None leaves initialization untruncated.
|
|
@@ -288,7 +353,36 @@ class GroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseRefitting):
|
|
|
288
353
|
|
|
289
354
|
def __init__(self, group_indices, rho_0=None, rho_k=None, rho_kl=None,
|
|
290
355
|
edge_distrib='normal', max_rank=None, init_rank=None, sigmas=None,
|
|
291
|
-
loops_allowed=True, n_jobs=None, refit_threshold=1e-8):
|
|
356
|
+
loops_allowed=True, n_jobs=None, refit_threshold=1e-8, c_rho=3.):
|
|
357
|
+
"""Initialize GroupMultiNeSS without fitting parameter matrices.
|
|
358
|
+
|
|
359
|
+
Parameters
|
|
360
|
+
----------
|
|
361
|
+
group_indices : list of int
|
|
362
|
+
Zero-based group assignment for each input layer; labels must span 0..K-1.
|
|
363
|
+
rho_0 : float or None, optional
|
|
364
|
+
Shared penalty; None uses c_rho * sqrt(n_layers * n_nodes).
|
|
365
|
+
rho_k : float or array-like or None, optional
|
|
366
|
+
Group penalties in group order; None uses c_rho * sqrt(group_size * n_nodes).
|
|
367
|
+
rho_kl : float or array-like or None, optional
|
|
368
|
+
Individual penalties in input-layer order; None uses c_rho * sqrt(n_nodes).
|
|
369
|
+
edge_distrib : str, optional
|
|
370
|
+
Edge distribution: 'normal', 'bernoulli', or 'poisson'.
|
|
371
|
+
max_rank : int or None, optional
|
|
372
|
+
Maximum fitted component rank; None uses floor(sqrt(n_nodes)).
|
|
373
|
+
init_rank : int or None, optional
|
|
374
|
+
Initialization rank; None leaves averages untruncated.
|
|
375
|
+
sigmas : float or array-like or None, optional
|
|
376
|
+
Positive Gaussian noise standard deviations, broadcastable over layers and edges.
|
|
377
|
+
loops_allowed : bool, optional
|
|
378
|
+
Whether diagonal entries contribute to fitting and expected adjacency.
|
|
379
|
+
n_jobs : int or None, optional
|
|
380
|
+
Number of joblib threads for independent group descents.
|
|
381
|
+
refit_threshold : float, optional
|
|
382
|
+
Eigenvalue magnitude below which component directions are omitted from refitting.
|
|
383
|
+
c_rho : float, default=3
|
|
384
|
+
Finite nonnegative multiplier for penalties left as None.
|
|
385
|
+
"""
|
|
292
386
|
BaseGroupMultiNeSSRefined.__init__(self, group_indices=group_indices, edge_distrib=edge_distrib,
|
|
293
387
|
max_rank=max_rank, init_rank=init_rank, sigmas=sigmas,
|
|
294
388
|
loops_allowed=loops_allowed, n_jobs=n_jobs)
|
|
@@ -297,13 +391,45 @@ class GroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseRefitting):
|
|
|
297
391
|
self.rho_0 = rho_0
|
|
298
392
|
self.rho_k = rho_k
|
|
299
393
|
self.rho_kl = rho_kl
|
|
394
|
+
self.c_rho = c_rho
|
|
300
395
|
|
|
301
396
|
def _compute_projected_map(self, idx, lr, key):
|
|
397
|
+
"""Construct the proximal projection for one parameter update.
|
|
398
|
+
|
|
399
|
+
Parameters
|
|
400
|
+
----------
|
|
401
|
+
idx : int
|
|
402
|
+
Index of the fitted parameter matrix.
|
|
403
|
+
lr : float or None, optional
|
|
404
|
+
Common step multiplier, divided by each matrix's layer participation count.
|
|
405
|
+
None uses 1 for Gaussian/Poisson and 3 for Bernoulli.
|
|
406
|
+
key : int
|
|
407
|
+
Optimization key: 0 for S, or 1..K for a group descent.
|
|
408
|
+
|
|
409
|
+
Returns
|
|
410
|
+
-------
|
|
411
|
+
callable
|
|
412
|
+
Matrix projection with the selected threshold and rank limit.
|
|
413
|
+
"""
|
|
302
414
|
mask = self._param_participance_masks[idx]
|
|
303
415
|
penalty = self._compute_penalty_coef(idx=idx, key=key)
|
|
304
416
|
return partial(soft_thresholding_operator, threshold=penalty * lr / mask.sum(), max_rank=self.max_rank)
|
|
305
417
|
|
|
306
418
|
def _compute_penalty_coef(self, idx, key):
|
|
419
|
+
"""Look up the penalty for a shared, group, or individual parameter matrix.
|
|
420
|
+
|
|
421
|
+
Parameters
|
|
422
|
+
----------
|
|
423
|
+
idx : int
|
|
424
|
+
Index of the fitted parameter matrix.
|
|
425
|
+
key : int
|
|
426
|
+
Optimization key: 0 for S, or 1..K for a group descent.
|
|
427
|
+
|
|
428
|
+
Returns
|
|
429
|
+
-------
|
|
430
|
+
float
|
|
431
|
+
Nuclear-norm penalty before participation and learning-rate scaling.
|
|
432
|
+
"""
|
|
307
433
|
params = self._key_2_hyperparams_dict[key]
|
|
308
434
|
if idx == 0:
|
|
309
435
|
return params['rho_0']
|
|
@@ -314,14 +440,19 @@ class GroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseRefitting):
|
|
|
314
440
|
return params['rho_kl'][idx_in_group]
|
|
315
441
|
|
|
316
442
|
def _make_key_2_hyperparams_dict(self):
|
|
317
|
-
|
|
443
|
+
"""Validate and resolve component penalties or oracle ranks for each descent.
|
|
444
|
+
"""
|
|
445
|
+
if np.ndim(self.c_rho) != 0:
|
|
446
|
+
raise ValueError('c_rho must be a scalar')
|
|
447
|
+
self._validate_penalty(self.c_rho, 'c_rho')
|
|
448
|
+
rho_0 = self.c_rho * np.sqrt(self.n_layers_ * self.n_nodes_) if self.rho_0 is None else self.rho_0
|
|
318
449
|
if not np.isscalar(rho_0):
|
|
319
450
|
raise ValueError('rho_0 must be a scalar')
|
|
320
451
|
rho_k = if_scalar_or_given_length_array(
|
|
321
|
-
|
|
452
|
+
self.c_rho * np.sqrt(self.group_sizes_ * self.n_nodes_) if self.rho_k is None else self.rho_k,
|
|
322
453
|
length=self.n_groups_, name='rho_k')
|
|
323
454
|
rho_kl = if_scalar_or_given_length_array(
|
|
324
|
-
|
|
455
|
+
self.c_rho * np.sqrt(self.n_nodes_) if self.rho_kl is None else self.rho_kl,
|
|
325
456
|
length=self.n_layers_, name='rho_kl')
|
|
326
457
|
self._validate_penalty(rho_0, 'rho_0')
|
|
327
458
|
self._validate_penalty(rho_k, 'rho_k')
|
|
@@ -330,118 +461,154 @@ class GroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseRefitting):
|
|
|
330
461
|
group + 1: {'rho_k': rho_k[group], 'rho_kl': rho_kl[self.group_indices == group]}
|
|
331
462
|
for group in self.unique_groups_}}
|
|
332
463
|
|
|
333
|
-
def fit(self, As, lr=None, max_iter=100, tol=1e-3, patience=
|
|
334
|
-
n_outer_iter=
|
|
335
|
-
save_latent_history=False, save_nll_history=True):
|
|
464
|
+
def fit(self, As, lr=None, max_iter=100, tol=1e-3, patience=1, refit=True,
|
|
465
|
+
n_outer_iter=20, verbose=False, verbose_interval=1,
|
|
466
|
+
save_latent_history=False, save_nll_history=True, save_convergence_history=True):
|
|
336
467
|
"""Fit Algorithm 1, then jointly refit every nonzero parameter matrix.
|
|
337
468
|
|
|
338
|
-
max_iter limits each group descent; n_outer_iter defaults to
|
|
469
|
+
max_iter limits each group descent; n_outer_iter defaults to 20 outer iterations.
|
|
339
470
|
tol and patience control consecutive small RFE changes in Q_k and S.
|
|
340
471
|
lr is a common scalar scale, divided once by each matrix's layer
|
|
341
472
|
participation count. Defaults are 1 for Gaussian/Poisson and 3 for Bernoulli.
|
|
342
473
|
All distributions use fixed steps without backtracking.
|
|
343
474
|
Each fit initializes all parameter matrices from the supplied data.
|
|
475
|
+
|
|
476
|
+
Parameters
|
|
477
|
+
----------
|
|
478
|
+
As : np.ndarray
|
|
479
|
+
Observed adjacency tensor with shape (n_layers, n_nodes, n_nodes);
|
|
480
|
+
NaN entries are excluded from the likelihood.
|
|
481
|
+
lr : float or None, optional
|
|
482
|
+
Common step multiplier, divided by each matrix's layer participation count.
|
|
483
|
+
None uses 1 for Gaussian/Poisson and 3 for Bernoulli.
|
|
484
|
+
max_iter : int, default=100
|
|
485
|
+
Maximum number of iterations per component descent.
|
|
486
|
+
tol : float, default=1e-3
|
|
487
|
+
Relative Frobenius change at or below which an iteration is stable.
|
|
488
|
+
patience : int, default=1
|
|
489
|
+
Number of consecutive stable component updates required to stop.
|
|
490
|
+
refit : bool, default=True
|
|
491
|
+
Jointly refit nonzero component directions after optimization.
|
|
492
|
+
n_outer_iter : int, default=20
|
|
493
|
+
Number of outer iterations to allocate or run; each contains group
|
|
494
|
+
descents followed by one shared update in GroupMultiNeSS.
|
|
495
|
+
verbose : bool, optional
|
|
496
|
+
Print NLL and the current RFE of S or Q_k at the requested interval.
|
|
497
|
+
verbose_interval : int, default=1
|
|
498
|
+
Print every this many iterations, starting at the first update.
|
|
499
|
+
save_latent_history : bool, default=False
|
|
500
|
+
Store latent matrix snapshots for ground-truth error plots.
|
|
501
|
+
Component convergence is saved independently.
|
|
502
|
+
save_nll_history : bool, default=True
|
|
503
|
+
Store NLL after each optimization step independently of latent history.
|
|
504
|
+
save_convergence_history : bool, default=True
|
|
505
|
+
Store one scalar RFE per component update for convergence plots,
|
|
506
|
+
without retaining matrices. False keeps only last_convergence_.
|
|
507
|
+
|
|
508
|
+
Returns
|
|
509
|
+
-------
|
|
510
|
+
self
|
|
511
|
+
Fitted model.
|
|
512
|
+
|
|
513
|
+
Notes
|
|
514
|
+
-----
|
|
515
|
+
Verbose output monitors Q_k inside each group descent and S after
|
|
516
|
+
each shared update. Scalar convergence, latent matrix, and NLL
|
|
517
|
+
histories are controlled independently.
|
|
344
518
|
"""
|
|
345
519
|
self._validate_optim_params(max_iter, tol, patience, verbose_interval, n_outer_iter)
|
|
346
520
|
lr = self._learning_rate(lr)
|
|
347
521
|
As = self._validate_input(As)
|
|
348
522
|
self._fit(As, lr=lr, n_outer_iter=n_outer_iter, max_iter=max_iter, tol=tol, patience=patience,
|
|
349
523
|
refit=refit, verbose=verbose, verbose_interval=verbose_interval,
|
|
350
|
-
save_latent_history=save_latent_history, save_nll_history=save_nll_history
|
|
524
|
+
save_latent_history=save_latent_history, save_nll_history=save_nll_history,
|
|
525
|
+
save_convergence_history=save_convergence_history)
|
|
351
526
|
return self
|
|
352
527
|
|
|
353
528
|
|
|
354
529
|
class GroupMultiNeSSCV(GroupMultiNeSS, BaseMultiNeSSRefinedCV):
|
|
355
|
-
"""GroupMultiNeSS with
|
|
530
|
+
"""GroupMultiNeSS with edge CV over one common penalty multiplier.
|
|
356
531
|
|
|
357
|
-
param_grid accepts
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
Default grids multiply each oracle rate by [0.03, 0.1, 0.3, 1, 3, 10].
|
|
532
|
+
param_grid accepts c_rho (default: [0.03, 0.1, 0.3, 1, 3, 10]) or rho_0.
|
|
533
|
+
Candidates set all penalties to their scaled values, replacing constructor
|
|
534
|
+
penalties. Each candidate completes the outer loop and optional joint refit.
|
|
361
535
|
"""
|
|
362
536
|
|
|
363
537
|
def __init__(self, group_indices, param_grid=None, edge_distrib='normal',
|
|
364
538
|
rho_0=None, rho_k=None, rho_kl=None, loops_allowed=True,
|
|
365
539
|
cv_folds=3, test_prop=0.1, max_rank=None, init_rank=None,
|
|
366
540
|
sigmas=None, n_jobs=None, refit_threshold=1e-8,
|
|
367
|
-
fix_layer_split=False, use_1se_rule=False, random_seed=None,
|
|
541
|
+
fix_layer_split=False, use_1se_rule=False, random_seed=None, c_rho=3.):
|
|
542
|
+
"""Initialize GroupMultiNeSSCV without fitting parameter matrices.
|
|
543
|
+
|
|
544
|
+
Parameters
|
|
545
|
+
----------
|
|
546
|
+
group_indices : list of int
|
|
547
|
+
Zero-based group assignment for each input layer; labels must span 0..K-1.
|
|
548
|
+
param_grid : dict or None, optional
|
|
549
|
+
One candidate sequence under 'c_rho' or 'rho_0'. None searches
|
|
550
|
+
c_rho in [0.03, 0.1, 0.3, 1, 3, 10]. Candidate penalties replace
|
|
551
|
+
constructor rho values using the common square-root scaling.
|
|
552
|
+
edge_distrib : str, optional
|
|
553
|
+
Edge distribution: 'normal', 'bernoulli', or 'poisson'.
|
|
554
|
+
rho_0 : float or None, optional
|
|
555
|
+
Shared penalty; None uses c_rho * sqrt(n_layers * n_nodes).
|
|
556
|
+
rho_k : float or array-like or None, optional
|
|
557
|
+
Group penalties in group order; None uses c_rho * sqrt(group_size * n_nodes).
|
|
558
|
+
rho_kl : float or array-like or None, optional
|
|
559
|
+
Individual penalties in input-layer order; None uses c_rho * sqrt(n_nodes).
|
|
560
|
+
loops_allowed : bool, optional
|
|
561
|
+
Whether diagonal entries contribute to fitting and expected adjacency.
|
|
562
|
+
cv_folds : int or None, optional
|
|
563
|
+
Number of repeated edge holdouts; None uses a single holdout.
|
|
564
|
+
test_prop : float, optional
|
|
565
|
+
Fraction of observed edges held out in each split, strictly between zero and one.
|
|
566
|
+
max_rank : int or None, optional
|
|
567
|
+
Maximum fitted component rank; None uses floor(sqrt(n_nodes)).
|
|
568
|
+
init_rank : int or None, optional
|
|
569
|
+
Initialization rank; None leaves averages untruncated.
|
|
570
|
+
sigmas : float or array-like or None, optional
|
|
571
|
+
Positive Gaussian noise standard deviations, broadcastable over layers and edges.
|
|
572
|
+
n_jobs : int or None, optional
|
|
573
|
+
Number of joblib threads for independent group descents.
|
|
574
|
+
refit_threshold : float, optional
|
|
575
|
+
Eigenvalue magnitude below which component directions are omitted from refitting.
|
|
576
|
+
fix_layer_split : bool, optional
|
|
577
|
+
Whether all layers use the same held-out edge positions.
|
|
578
|
+
use_1se_rule : bool, optional
|
|
579
|
+
Choose the largest candidate within one standard error of the minimum mean NLL.
|
|
580
|
+
random_seed : int or None, optional
|
|
581
|
+
Seed for reproducible training and held-out edge splits.
|
|
582
|
+
c_rho : float, default=3
|
|
583
|
+
Finite nonnegative multiplier for penalties left as None.
|
|
584
|
+
"""
|
|
368
585
|
BaseMultiNeSSRefinedCV.__init__(self, param_grid=param_grid, cv_folds=cv_folds,
|
|
369
586
|
test_prop=test_prop, loops_allowed=loops_allowed,
|
|
370
587
|
fix_layer_split=fix_layer_split, use_1se_rule=use_1se_rule,
|
|
371
|
-
random_seed=random_seed
|
|
588
|
+
random_seed=random_seed)
|
|
372
589
|
GroupMultiNeSS.__init__(self, group_indices=group_indices, rho_0=rho_0, rho_k=rho_k,
|
|
373
590
|
rho_kl=rho_kl, edge_distrib=edge_distrib, max_rank=max_rank,
|
|
374
591
|
init_rank=init_rank, sigmas=sigmas, loops_allowed=loops_allowed,
|
|
375
|
-
n_jobs=n_jobs, refit_threshold=refit_threshold)
|
|
376
|
-
|
|
377
|
-
def _make_key_2_hyperparams_grid_dict(self):
|
|
378
|
-
allowed = {'rho_0', 'rho_k'} if self.cv_type == 'full' else {'rho_0'}
|
|
379
|
-
if self.param_grid is not None and set(self.param_grid) - allowed:
|
|
380
|
-
raise ValueError(f'{self.cv_type} CV param_grid only accepts {sorted(allowed)}')
|
|
381
|
-
BaseMultiNeSSRefinedCV._make_key_2_hyperparams_grid_dict(self)
|
|
382
|
-
if self.cv_type == 'full':
|
|
383
|
-
group_grid = None if self.param_grid is None else self.param_grid.get('rho_k')
|
|
384
|
-
if isinstance(group_grid, dict) and set(group_grid) - set(self.unique_groups_):
|
|
385
|
-
raise ValueError('rho_k grids must use existing zero-based group labels')
|
|
386
|
-
self._key_2_hyperparams_grid.update({group + 1: {'rho_k': self._penalty_grid(
|
|
387
|
-
'rho_k', np.sqrt(self.n_nodes_ * self.group_sizes_[group]), group=group)}
|
|
388
|
-
for group in self.unique_groups_})
|
|
592
|
+
n_jobs=n_jobs, refit_threshold=refit_threshold, c_rho=c_rho)
|
|
389
593
|
|
|
390
594
|
def _set_cv_penalties(self, params, key):
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
def _cv_full(self, As, n_outer_iter, refit, optim_kwargs):
|
|
410
|
-
# Keep a fold's group fits with its own S initializer and edge mask. S CV
|
|
411
|
-
# uses these same training/test edges, never full-data group estimates.
|
|
412
|
-
folds = []
|
|
413
|
-
lr = self._learning_rate(optim_kwargs['lr'])
|
|
414
|
-
inner_kwargs = {**optim_kwargs, 'lr': lr}
|
|
415
|
-
with ExitStack() as stack:
|
|
416
|
-
for train, test in self._cv_splits(As):
|
|
417
|
-
candidate = stack.enter_context(closing(self._new_cv_model(train, n_outer_iter)))
|
|
418
|
-
initial = candidate.get_all_fitted_matrices().copy()
|
|
419
|
-
folds.append((candidate, train, test, initial))
|
|
420
|
-
for key in range(1, self.n_groups_ + 1):
|
|
421
|
-
mask = candidate._param_participance_masks[key]
|
|
422
|
-
for params in self._cv_results[key]:
|
|
423
|
-
candidate._set_matrices(initial)
|
|
424
|
-
candidate._set_cv_penalties({'rho_k': params[0]}, key)
|
|
425
|
-
candidate._optimize_params(key=key, As=train, **inner_kwargs)
|
|
426
|
-
self._cv_results[key][params].append(candidate._compute_nll(test, obs_mask=mask))
|
|
427
|
-
for key in range(1, self.n_groups_ + 1):
|
|
428
|
-
self._set_best_hyperparams(key)
|
|
429
|
-
for candidate, train, test, initial in folds:
|
|
430
|
-
candidate._set_matrices(initial)
|
|
431
|
-
candidate._key_2_hyperparams_dict = deepcopy(self._key_2_hyperparams_dict)
|
|
432
|
-
for key in range(1, self.n_groups_ + 1):
|
|
433
|
-
candidate._optimize_params(key=key, As=train, **inner_kwargs)
|
|
434
|
-
group_fitted = candidate.get_all_fitted_matrices().copy()
|
|
435
|
-
for params in self._cv_results[0]:
|
|
436
|
-
candidate._set_matrices(group_fitted)
|
|
437
|
-
candidate._set_cv_penalties({'rho_0': params[0]}, 0)
|
|
438
|
-
candidate._optimization_step([0], key=0, As=train, lr=lr, iteration=0,
|
|
439
|
-
outer_iter=0, verbose=False, tol=optim_kwargs['tol'],
|
|
440
|
-
save_latent_history=False, save_nll_history=False)
|
|
441
|
-
if refit:
|
|
442
|
-
candidate.refit(train)
|
|
443
|
-
self._cv_results[0][params].append(candidate._compute_nll(test))
|
|
444
|
-
self._set_best_hyperparams(0)
|
|
595
|
+
"""Apply a candidate's common scaling to every component penalty.
|
|
596
|
+
|
|
597
|
+
Parameters
|
|
598
|
+
----------
|
|
599
|
+
params : dict
|
|
600
|
+
One selected c_rho or rho_0 value defining all linked penalties.
|
|
601
|
+
key : int
|
|
602
|
+
Optimization key: 0 for S, or 1..K for a group descent.
|
|
603
|
+
"""
|
|
604
|
+
rho_0 = (params['c_rho'] * np.sqrt(self.n_layers_ * self.n_nodes_)
|
|
605
|
+
if 'c_rho' in params else params['rho_0'])
|
|
606
|
+
self._set_hyperparams({'rho_0': rho_0}, key)
|
|
607
|
+
for group in self.unique_groups_:
|
|
608
|
+
self._key_2_hyperparams_dict[group + 1]['rho_k'] = (
|
|
609
|
+
rho_0 * np.sqrt(self.group_sizes_[group] / self.n_layers_))
|
|
610
|
+
self._key_2_hyperparams_dict[group + 1]['rho_kl'] = np.full(
|
|
611
|
+
self.group_sizes_[group], rho_0 / np.sqrt(self.n_layers_))
|
|
445
612
|
|
|
446
613
|
|
|
447
614
|
class OracleGroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseOracleMultiNeSS):
|
|
@@ -451,6 +618,27 @@ class OracleGroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseOracleMultiNeSS):
|
|
|
451
618
|
sigmas: Optional[Union[float, List[float], np.ndarray]] = None,
|
|
452
619
|
loops_allowed: bool = True,
|
|
453
620
|
n_jobs: Optional[int] = None):
|
|
621
|
+
"""Initialize OracleGroupMultiNeSS without fitting parameter matrices.
|
|
622
|
+
|
|
623
|
+
Parameters
|
|
624
|
+
----------
|
|
625
|
+
group_indices : list of int
|
|
626
|
+
Zero-based group assignment for each input layer; labels must span 0..K-1.
|
|
627
|
+
d_shared : int
|
|
628
|
+
Fixed rank of the shared component.
|
|
629
|
+
d_groups : array-like of int
|
|
630
|
+
Fixed rank for each group component, in group order.
|
|
631
|
+
d_individs : int or array-like of int
|
|
632
|
+
Fixed individual ranks, supplied as a scalar or in input-layer order.
|
|
633
|
+
edge_distrib : str, optional
|
|
634
|
+
Edge distribution: 'normal', 'bernoulli', or 'poisson'.
|
|
635
|
+
sigmas : float or array-like or None, optional
|
|
636
|
+
Positive Gaussian noise standard deviations, broadcastable over layers and edges.
|
|
637
|
+
loops_allowed : bool, optional
|
|
638
|
+
Whether diagonal entries contribute to fitting and expected adjacency.
|
|
639
|
+
n_jobs : int or None, optional
|
|
640
|
+
Number of joblib threads for independent group descents.
|
|
641
|
+
"""
|
|
454
642
|
|
|
455
643
|
BaseGroupMultiNeSSRefined.__init__(self, group_indices=group_indices,
|
|
456
644
|
edge_distrib=edge_distrib, sigmas=sigmas,
|
|
@@ -460,6 +648,8 @@ class OracleGroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseOracleMultiNeSS):
|
|
|
460
648
|
self.d_individs = d_individs
|
|
461
649
|
|
|
462
650
|
def _make_key_2_hyperparams_dict(self):
|
|
651
|
+
"""Validate and resolve component penalties or oracle ranks for each descent.
|
|
652
|
+
"""
|
|
463
653
|
d_shared = int(if_scalar_or_given_length_array(self.d_shared, length=1, name='d_shared')[0])
|
|
464
654
|
d_groups = if_scalar_or_given_length_array(self.d_groups, length=self.n_groups_, name='d_groups')
|
|
465
655
|
d_individs = if_scalar_or_given_length_array(self.d_individs, length=self.n_layers_, name='d_individs')
|
|
@@ -469,6 +659,20 @@ class OracleGroupMultiNeSS(BaseGroupMultiNeSSRefined, BaseOracleMultiNeSS):
|
|
|
469
659
|
for group in self.unique_groups_}}
|
|
470
660
|
|
|
471
661
|
def _compute_threshold_rank(self, idx, key):
|
|
662
|
+
"""Look up the fixed rank for a shared, group, or individual component.
|
|
663
|
+
|
|
664
|
+
Parameters
|
|
665
|
+
----------
|
|
666
|
+
idx : int
|
|
667
|
+
Index of the fitted parameter matrix.
|
|
668
|
+
key : int
|
|
669
|
+
Optimization key: 0 for S, or 1..K for a group descent.
|
|
670
|
+
|
|
671
|
+
Returns
|
|
672
|
+
-------
|
|
673
|
+
int
|
|
674
|
+
Rank used by the hard-thresholding projection.
|
|
675
|
+
"""
|
|
472
676
|
params = self._key_2_hyperparams_dict[key]
|
|
473
677
|
if idx == 0:
|
|
474
678
|
return params['d_shared']
|