You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
|None=None, # TODO This isn't a TensorVariable, not sure what the general datatype for numeric arraylikes is
423
+
x0: TensorLike|None=None,
426
424
model: pm.Model|None=None,
427
425
method: minimize_method="BFGS",
428
426
use_jac: bool=True,
429
-
use_hess: bool=False,
427
+
use_hess: bool=False,# TODO Tbh we can probably just remove this arg and pass True to the minimizer all the time, but if this is the case, it will throw a warning when the hessian doesn't need to be computed for a particular optimisation routine.
430
428
optimizer_kwargs: dict|None=None,
431
-
): # TODO Output type is list of same type as x0
429
+
) ->list[TensorLike]:
430
+
"""
431
+
Estimates the mode and hessian of a model by minimizing negative log likelihood. Wrapper for (pytensor-native) scipy.optimize.minimize.
432
+
433
+
Parameters
434
+
----------
435
+
x: TensorVariable
436
+
The parameter with which to minimize wrt (that is, find the mode in x).
437
+
args: dict
438
+
A dictionary of the form {tensorvariable_name: TensorLike}, where tensorvariable_name is the (exact) name of TensorVariable which is to be provided some numerical value. Same usage as args in scipy.optimize.minimize.
439
+
x0: TensorLike
440
+
Initial guess for the mode (in x). Initialised over a uniform distribution if unspecified.
441
+
model: Model
442
+
PyMC model to use.
443
+
method: minimize_method
444
+
Which minimization algorithm to use.
445
+
use_jac: bool
446
+
If true, the minimizer will compute and store the Jacobian.
447
+
use_hess: bool
448
+
If true, the minimizer will compute and store the Hessian (note that the Hessian will be computed explicitely even if this is False).
449
+
optimizer_kwargs: dict
450
+
Kwargs to pass to scipy.optimize.minimize.
451
+
452
+
Returns
453
+
-------
454
+
mu: TensorLike
455
+
The mode of the model.
456
+
hess:
457
+
Hessian evalulated at mu.
458
+
"""
432
459
model=pm.modelcontext(model)
433
460
434
-
# if x0 is None:
435
-
# #TODO Issue with X not being an RV
436
-
# print(model.initial_point())
461
+
# # TODO I would like to generate a random initialisation for x0 if set to None. Ideally this would be done using something like np.random.rand(x.shape), however I don't believe x.shape is
462
+
# # immediately accessible in pytensor. model.initial_point() throws the following error:
463
+
464
+
# # MissingInputError: Input 0 (X) of the graph (indices start from 0), used to compute Transpose{axes=[1, 0]}(X), was not provided and not given a value. Use the PyTensor flag exception_verbosity='high', for more information on this error.
437
465
466
+
# # Instead I've tried to follow what find_MAP does (below), but this doesn't really get me anywhere unfortunately.
467
+
# # if x0 is None:
468
+
# # Yes ik this is here, just for debugging purposes
438
469
# from pymc.initial_point import make_initial_point_fn
470
+
439
471
# frozen_model = freeze_dims_and_data(model)
440
472
# ipfn = make_initial_point_fn(
441
-
# model=model,
442
-
# jitter_rvs=set(),#(jitter_rvs),
473
+
# model=frozen_model,
474
+
# jitter_rvs=set(), # (jitter_rvs),
443
475
# return_transformed=True,
444
-
# overrides=args,
476
+
# overrides={x.name: x0}, # x0 is here for debugging purposes
445
477
# )
446
478
447
479
# random_seed = None
@@ -450,6 +482,7 @@ def find_mode(
450
482
# initial_params = DictToArrayBijection.map(
451
483
# {var_name: value for var_name, value in start_dict.items() if var_name in vars_dict}
452
484
# )
485
+
# # Printing this should return {'name of x TensorVariable': initialised values for x}
# TODO To prevent needing to user to pass in the TensorVariables alongside their names (e.g. args = {'X': [X, [0,0]], 'beta': [beta_val, [1]], ...}) the codeblock below digs up the
500
+
# TensorVariables associated with the names listed in args from the graph. The sensible graph to use here would be nll, because that is what is going into the minimize function, however doing
501
+
# so results in the following error:
502
+
#
503
+
# TypeError: TensorType does not support iteration.
504
+
# Did you pass a PyTensor variable to a function that expects a list?
505
+
# Maybe you are using builtins.sum instead of pytensor.tensor.sum?
506
+
#
507
+
# Using model.basic_RVs[1] instead works, but note that this is a hardcoded fix because the model I'm testing on happens to have all of the relevant TensorVariables in the graph of model.basic_RVs[1],
# TODO: Jesse suggested I use this graph_replace function, but it seems that "mode" here is a different type to soln:
524
+
#
525
+
# TypeError: Cannot convert Type Vector(float64, shape=(10,)) (of Variable MinimizeOp(method=BFGS, jac=True, hess=True, hessp=False).0) into Type Scalar(float64, shape=()). You can try to manually convert MinimizeOp(method=BFGS, jac=True, hess=True, hessp=False).0 into a Scalar(float64, shape=()).
526
+
#
527
+
# My understanding here is that for some function which evaluates the hessian at x, we're replacing "x" in the hess graph with the subgraph that computes "x" (i.e. soln)?
479
528
480
529
# Obtain the Hessian (re-use graph if already computed in minimize)
481
530
ifuse_hess:
482
-
hess=soln.owner.op.inner_outputs[-1]
483
-
hess=pytensor.graph.replace.graph_replace(
484
-
hess, {x: soln}
485
-
) # TODO: x here is 'beta', soln is a MinimizeOp. There's no instance of MinimizeOp in the hessian graph
531
+
mode, _, hess=(
532
+
soln.owner.op.inner_outputs
533
+
) # Note that this mode, _, hess will need to be slightly more elaborate for when use_jac is False (2 items to unpack instead of 3). Just a few if-blocks, but not implemented for now while we're debugging
0 commit comments