1

I have this small < 100 lines of Python code:

Where I'm getting the error:

index = index + consistent_index
UnboundLocalError: local variable 'consistent_index' referenced before assignment

I tried to declare consistent_index as global variable, but it's still throwing the same error. Can you please have a short look at the code and help me?

import rrcf
import numpy as np
from flask import Flask
from flask import request

# ml code, generate tree
# Set tree parameters
num_trees = 40
shingle_size = 4
tree_size = 256

# Create a forest of empty trees
forest = []
for _ in range(num_trees):
    tree = rrcf.RCTree()
    forest.append(tree)
# ml code, generate tree

consistent_index = 0

app = Flask(__name__)

@app.route("/anomaly", methods=['GET', 'POST'])
def anomaly():
    # Use the "shingle" generator to create rolling window
    points = rrcf.shingle(request.get_json()['points'], size=shingle_size)

    # Create a dict to store anomaly score of each point
    avg_codisp = {}
    highest_index = 0

    # For each shingle...
    for index, point in enumerate(points):
        index = index + consistent_index
        highest_index = index
        # For each tree in the forest...
        for tree in forest:
            # If tree is above permitted size...
            if len(tree.leaves) > tree_size:
                # Drop the oldest point (FIFO)
                tree.forget_point(index - tree_size)
            # Insert the new point into the tree
            tree.insert_point(point, index=index)
            # Compute codisp on the new point...
            new_codisp = tree.codisp(index)
            # And take the average over all trees
            if not index in avg_codisp:
                avg_codisp[index] = 0
            avg_codisp[index] += new_codisp / num_trees

    consistent_index += highest_index

    return "Hello, World!: " + str(avg_codisp)

if __name__ == "__main__":
    app.run(debug=True)
John Smith
  • 6,105
  • 16
  • 58
  • 109
  • 1
    Well, what _is_ `consistent_index`? What is it equal to at the beginning of the loop? In other words, _what number_ are you adding to `index`? This code doesn't answer any of these questions because it never initializes this variable. – ForceBru Jul 24 '19 at 10:38
  • @ForceBru but I have: `consistent_index = 0` outside of the loop correct? Can you maybe explain more and post a answer? Thanks – John Smith Jul 24 '19 at 10:43

1 Answers1

1

You probably have to use the global keyword in your function.

def anomaly():
    global consistent_index
    ... # rest of your code

https://docs.python.org/3/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value

Fredrik
  • 431
  • 3
  • 7