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)