UnboundLocalError: local variable 'dist' referenced before assignment

1.2k Views Asked by At

I am trying to train a model for supervised learning for Hidden Markov Model (HMM)and test it on a set of observations however, keep getting this error. The goal is to predict the state based on the observations. How can I fix this and how can I view the transition matrix?

The version for Pomegranate is 0.14.4 Trying this from the source: https://github.com/jmschrei/pomegranate/issues/1005

from pomegranate import *
import numpy as np
# Supervised method that calculates the transition matrix:
d1 = State(UniformDistribution.from_samples([3.243221498397177, 3.210684537495482, 3.227662201472816,
    3.286410817416738, 3.290573650708864, 3.286058136226862, 3.266480693857006]))
d2 = State(UniformDistribution.from_samples([3.449282367485096, 1.97317859465635, 1.897551432353011,
     3.454609351559659, 3.127357456033111, 1.779308337786426, 3.802891929694426, 3.359766157565077, 2.959428499979418]))
d3 = State(UniformDistribution.from_samples([1.892812118441474, 1.589353118681066, 2.09269978285637,
     2.104391496570218, 1.656771181054144]))
model = HiddenMarkovModel()
model.add_states(d1, d2, d3)
# print(model.to_json())
model.bake()
model.fit([3.2, 6.7, 10.55], labels=[1, 2, 3], algorithm='labeled')
all_pred = model.predict([2.33, 1.22, 1.4, 10.6])

Error:

 File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2\plugins\python-ce\helpers\pydev\_pydev_bundle\pydev_umd.py", line 198, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "C:\Program Files\JetBrains\PyCharm Community Edition 2021.2\plugins\python-ce\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/", line 774, in <module>
    model.bake()
  File "pomegranate/hmm.pyx", line 1047, in pomegranate.hmm.HiddenMarkovModel.bake
UnboundLocalError: local variable 'dist' referenced before assignment
1

There are 1 best solutions below

0
On

Seems like a bug in promegranate.

This Python UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a function.

Observing the hmm.pyx code, dist is assigned a value in a function's body(which is a local variable) and not declared as global. To solve the error, mark the variable as global in the function definition,

e.g. global dist

Try adding dist variable in your code that you provided. For e.g. Hope this helps!